2016-07-18 58 views
-2

我有兩個表A和B.如何顯示SQL中兩個表之間的一對多關係?

一個表包含

postid,postname,CategoryURl 

乙表包含

postid,CategoryImageURL 

對於一個帖子ID有多個CategoryImageURL assigned.I希望要在表A中顯示CategoryImageURL,但對於一個postid,應該有CategoryImageURL1,CategoryImageURL2應該像那樣。

我想爲一個postid實現一對多的關係,那麼在sql函數中應該返回什麼邏輯?

+0

否決 - 請考慮更改標題。標題應該包含你的問題的簡要說明,而不是「你好,我是新的...」 –

+0

你是新來的asp.net,但這個問題是不相關的。 – Imad

+0

這屬於表現層面,請在那裏處理。 – dean

回答

0

你在問錯誤的問題。這是關於正常化。

就目前而言,你有冗餘嗎?其中每個postname和categoryURL由一個ID字段表示。

無論出於何種原因,表將CategoryImageUrl分隔到自己的表中,並將其鏈接到每組postname和categoryURL。

如果關係實際上是每個帖子的一個id,那麼可以通過將CategoryImageUrl添加到第一個表中來非規範化該表。

帖子ID,postname,CategoryURL,CategoryImageUrl

或者,如果你想保留正常化,結合像場到自己的表像這樣:

--TableA: 
Postid, postname, <any other field dependent on postname > 
--TableA 
Postid, CategoryURL, CategoryImageUrl 

現在,這個羣體CategoryURL在一起,但採用了冗餘有多個CategoryURL存在。但是,Postid只有一個CategoryUrl。

要在我們的表中刪除這種冗餘,我們可以使用一個Star Schema策略是這樣的:

-- Post Table 
Postid, postname 

-- Category table 
CategoryID, CategoryURL, <any other info dependent only on CategoryURL> 

-- Fact Table 
Postid, CategoryID, CategoryImageURL 

免責聲明:當然,我認爲你的數據的方面,並可能會關閉。但是,正常化的策略仍然是一樣的。

另外,請記住,SQL是關係型的,可處理數據集。繼承與關係集合理論不兼容。每張桌子都可以向前和向後查詢,書中的每一頁和每一章都被視爲本書的一部分。我們從來沒有看到獨立於書的章節。

1

在我看來,你想要顯示在同一個分隔符在這種情況下逗號的第二個表的所有相關的CategoryImageURLs? 然後你需要在那裏遞歸操作。也許一個CTE(公用表表達式)可以做到這一點。見下文。我已經在第二個表中添加了另一個關鍵字,以便能夠檢查第二個表的所有行是否已經爲第一個表中的對應行進行處理。

也許這會有所幫助:

with a_cte (post_id, url_id, name, list, rrank) as 
(
    select 
     a.post_id 
     , b.url_id 
     , a.name 
     , cast(b.urln + ', ' as nvarchar(100)) as list 
     , 0 as rrank 
    from 
     dbo.a 
    join dbo.b 
     on a.post_id = b.post_id 
union all 
    select 
     c.post_id 
     , a1.url_id 
     , c.name 
     , cast(c.list + case when rrank = 0 then '' else ', ' end + a1.urln as nvarchar(100)) 
     , c.rrank + 1 
    from a_cte c 
    join ( select 
       b.post_id 
       , b.url_id 
       , a.name 
       , b.urln 
      from dbo.a 
      join dbo.b 
      on a.post_id = b.post_id 
        ) a1 
    on c.post_id = a1.post_id 
    and c.url_id < a1.url_id -- ==> take care, that there is no endless loop 
) 
select d.name, d.list 
from 
    (
    select name, list, rank() over (partition by post_id order by rrank desc) 
    from a_cte 
    ) d (name, list, rank) 
where rank = 1 
相關問題