2

I want to join table Documents(id, name) and Tags(tagId, tagname, docId(FK)). However result will return many redundant rows because one document can has many tags:

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

All I try to resolve is:

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

or can be like this:

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

Anyone know how can implement this case? Thanks a lot! (I'm trying to find other answer in this site, but I don't know suitable keyword to search in this case)

fdomig
  • 4,417
  • 3
  • 26
  • 39
Azzurri
  • 63
  • 2
  • 9
  • [This can be helpfull][1] I specially like the one with the STUFF clause [1]: http://stackoverflow.com/questions/451415/simulating-group-concat-mysql-function-in-ms-sql-server-2005 – Yaroslav Jul 05 '12 at 06:23

3 Answers3

2

if you are using MySQL you can do this:

select document_name, group_concat(tag SEPARATOR ', ')
from Documents
group by document_name
juergen d
  • 201,996
  • 37
  • 293
  • 362
  • I'm using SQL Server 2008, is it have any function like group_concat()? – Azzurri Jul 05 '12 at 06:16
  • MSSQL does not have that function. But you can search on stackoverflow for questions like `group_concat for sql-server` and you will find workarounds. – juergen d Jul 05 '12 at 06:17
1

For MS-SQL try this

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
yogi
  • 19,175
  • 13
  • 62
  • 92
0

In 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

Result:


document_name |Tags
----------------------------
document01    | tag01, tag02
document02    | tag01
Nikson Kanti Paul
  • 3,394
  • 1
  • 35
  • 51