2013-10-19 73 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>