2013-10-19 76 views
1

我正在寫一個類似於博客軟件的網絡應用程序。顯示所有條目標籤

並希望顯示由標籤分類的博客文章後,輸出到客戶端應該是:

--PostID 1-- 
--PostContent 1-- 
--Tags : tag1 , tag2 -- 

--PostID 2-- 
--PostContent 2-- 
--Tags : tag1 , tag2, tag3 -- 

--PostID 3-- 
--PostContent 3-- 
--Tags : tag3 , tag4-- 

所以我使用的查詢,如:

Select PostTitle, PostContent from tblBlogPost ...

但這些標籤位於在具有以下結構的新表格中:

PostID PostTag 
1  tag1 
1  tag2 
2  tag1 
2  tag2 
2  tag3 
3  tag3 
3  tag4 

所以我如何將標籤列表添加到我的查詢中?

+0

可能重複的[如何變換從基於特定的列到另一個數據結構的行數據(http://stackoverflow.com/questions/19144535/how-to-transform-data-from-rows -based-on-a-specific-column-to-another-data-struc) –

回答

0

您可以使用pivot,你可以看到詳細的解答在這裏:
How to transform data from rows based on a specific column to another data structure

你只需要使用您的PostID的每一個代碼(除非你不在乎有一些空值標籤 - >然後你可以在一個查詢做到這一點):

爲=帖子ID 2的一個例子:

select PostID, Tag1, Tag2, Tag3 
from 
(
    select id, 
    col = col + cast(seq as varchar(10)), 
    value 
    from 
    (
    select PostID, PostTag 
     , row_number() over(partition by PostID 
          order by PostID) seq 
    WHERE PostId = 2 
    from yourtable 
) t 
    cross apply 
    (
    select 'Tag', PostTag 
) c (col, value) 
) d 
pivot 
(
    max(value) 
    for col in (Tag1, Tag2, Tag3) 
) piv; 
+0

如果我有無限制的標籤會發生什麼? – monocular

+0

這仍然不是問題,您可以在我附加的帖子中看到答案,它有一個部分描述瞭如何在不假設任何列的情況下執行此操作。 –

0

如果你可以在你的申請解析XML或XSLT我會考慮使用sqlxml。類似這樣的查詢

select 
    top 1 Post, 
    (
    select 
     Tag 

    from Posts_Tags bb 
    where aa.Post= bb.Post 
for xml raw ('Tags'), type 
    ) as users 
From Posts aa 
for xml raw('Posts'), type 

會返回類似這樣的東西;

<Posts Post="Post1"> 
    <Tags> 
    <Tags Tag="A" /> 
    <Tags Tag="B" /> 
    <Tags Tag="C" /> 
    </Tags> 
</PostTags>