Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all the tags of each page and then concat the tags into one column?

How can I find all the tags of each page and then concat the tags into one column?

For an example,

pages table,

page_id 
1
2
3
4

tags table,

tag_id      tag_name
1           A
2           B
3           C
4           D

tagged table,

page_id     tag_id
1           1
1           2
1           3
3           2
3           3

My working query,

SELECT
    p.page_id,
    GROUP_CONCAT(t.tag_name ORDER BY t.tag_name ASC SEPARATOR ",") AS tags

FROM root_pages AS p

LEFT JOIN root_mm_pages_tags AS m
ON p.page_id = m.page_id

LEFT JOIN root_tags AS t
ON t.tag_id = m.tag_id

WHERE p.page_id = t.page_id

This is the result I am after,

page_id         tags
1               A, B, C
2               NULL
3               B, C
4               NULL
like image 493
Run Avatar asked Nov 15 '11 23:11

Run


1 Answers

try it without ON p.page_id = tt.page_id and WHERE p.page_id = t.page_id; also make the last join a regular one for performance.

SELECT
    p.page_id,
    GROUP_CONCAT(t.tag_name ORDER BY t.tag_name ASC SEPARATOR ",") AS tags

FROM root_pages AS p

LEFT JOIN root_mm_pages_tags AS m
ON p.page_id = m.page_id

JOIN root_tags AS t
ON t.tag_id = m.tag_id

GROUP BY p.page_id
like image 142
toon81 Avatar answered Sep 29 '22 12:09

toon81