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

那么如何将标签列表包含到我的查询中呢?

4

2 回答 2

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;
于 2013-10-19T11:10:56.687 回答
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>
于 2013-10-19T11:20:34.137 回答