Combining multiple fields into one with SQL

I have three tables tag, page,pagetag

With the data below

page

ID      NAME
1       page 1
2       page 2
3       page 3
4       page 4

tag

ID      NAME
1       tag 1
2       tag 2
3       tag 3
4       tag 4

pagetag

ID   PAGEID  TAGID
1    2        1
2    2        3
3    3        4
4    1        1
5    1        2
6    1        3

I would like to get a string containing the corresponding tag names for each page with SQL in one query. This is my desired result.

ID      NAME       TAGS
1       page 1     tag 1, tag 2, tag 3
2       page 2     tag 1, tag 3
3       page 3     tag 4
4       page 4    

Is this possible with SQL?


I am using MySQL. However, I would like, if possible, an independent solution from the database provider.

+5
source share
6 answers

Sergio del Amo:

However, I do not get pages without tags. I think I need to write my query with left outer joins.

SELECT pagetag.id, page.name, group_concat(tag.name)
FROM
(
    page LEFT JOIN pagetag ON page.id = pagetag.pageid
)
LEFT JOIN tag ON pagetag.tagid = tag.id
GROUP BY page.id;

, , - pagetag.id group_concat(tag.name) null 4 , .

+3

, 3, :

SELECT page_tag.id, page.name, group_concat(tags.name)
FROM tag, page, page_tag
WHERE page_tag.page_id = page.page_id AND page_tag.tag_id = tag.id;

, , , !

, MySQL, MSSQL! MySQL , .

+3

, SQL92 , . , .

, .

( , Oracle)

Oracle

SELECT field1 | ', ' | field2
FROM table;

MS SQL

SELECT field1 + ', ' + field2
FROM table;

MySQL

SELECT concat(field1,', ',field2)
FROM table;

PostgeSQL

SELECT field1 || ', ' || field2
FROM table;
+1

, . :

SELECT
    page.id AS id,
    page.name AS name,
    tagstable.tags AS tags
FROM page 
LEFT OUTER JOIN 
(
    SELECT pagetag.pageid, GROUP_CONCAT(distinct tag.name) AS tags
    FROM tag INNER JOIN pagetag ON tagid = tag.id
    GROUP BY pagetag.pageid
)
AS tagstable ON tagstable.pageid = page.id
GROUP BY page.id

:

id   name    tags
---------------------------
1    page 1  tag2,tag3,tag1
2    page 2  tag1,tag3
3    page 3  tag4
4    page 4  NULL

, ?

+1

, .

- ( ):

select ID as 'PageId', Name as 'PageName', null as 'Tags'
into #temp 
from [PageTable]

declare @lastOp int
set @lastOp = 1

while @lastOp > 0
begin
    update p
    set p.tags = isnull(tags + ', ', '' ) + t.[Tagid]
    from #temp p
        inner join [TagTable] t
            on p.[PageId] = t.[PageId]
    where p.tags not like '%' + t.[Tagid] + '%'

    set  @lastOp == @@rowcount
end

select * from #temp

, .

T-SQL, , MySql , .

0

pagetag.id group_concat (tag.name) 4 , .

COALESCE , :

select COALESCE(pagetag.id, '') AS id ...

.

0

All Articles