【问题标题】:How to display SQL result like that如何显示这样的 SQL 结果
【发布时间】:2012-07-05 19:51:32
【问题描述】:

我想加入表格 Documents(id, name) 和 Tags(tagId, tagname, docId(FK))。但是结果会返回很多冗余行,因为一个文档可以有很多标签:

Document_name |Tag
----------------------
document01     tag01
document01     tag02
document02     tag01

我试图解决的只是:

document_name |Tags
----------------------------
document01    | tag01, tag02
document02    | tag01

或者可以是这样的:

Document_name |Tag_1   |Tag_2  |Tag_...
---------------------------------------
document01     tag01  |tag02
document02     tag01

有人知道如何实现这种情况吗?非常感谢! (我试图在这个网站上找到其他答案,但我不知道在这种情况下搜索合适的关键字)

【问题讨论】:

标签: sql join


【解决方案1】:

如果你使用 MySQL,你可以这样做:

select document_name, group_concat(tag SEPARATOR ', ')
from Documents
group by document_name

【讨论】:

  • 我用的是SQL Server 2008,有group_concat()这样的功能吗?
  • MSSQL 没有这个功能。但是你可以在stackoverflow上搜索group_concat for sql-server之类的问题,你会找到解决方法。
【解决方案2】:

对于 MS-SQL 试试这个

select 
    d1.Document_name, 
    ( 
        select d2.Tag +','
        from Docs d2
        where d2.Document_name = d1.Document_name
        for xml path('')
    ) as Tags
from Docs d1
group by d1.Document_name

【讨论】:

    【解决方案3】:

    在 MySQL 中:

    SELECT doc.name, GROUP_CONCAT( tag.tagname SEPARATOR ', ') 
           FROM documents AS doc
           JOIN Tags AS tag ON doc.id = tag.docId
           GROUP BY tag.docId
    

    结果:

    
    document_name |Tags
    ----------------------------
    document01    | tag01, tag02
    document02    | tag01
    

    【讨论】:

    • OP 说他使用的是 SQL Server 2008。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 2017-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多