显示所有项目标签

时间:2013-10-19 11:06:25

标签: sql-server

我正在编写类似于博客软件的Web应用程序。

要显示按标签分类的博客文章,输出到客户端应为:

--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

那么如何将标记列表包含在我的查询中?

2 个答案:

答案 0 :(得分:0)

您可以使用pivot,您可以在此处看到详细答案:
How to transform data from rows based on a specific column to another data structure

您只需为每个PostID使用此代码(除非您不关心某些标记的NULL值 - >然后您可以在一个查询中执行此操作):

PostID = 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;

答案 1 :(得分: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>