简体   繁体   中英

Concat column MYSQL

I Have this select

SELECT page.*, page_lang.*, category.title as category FROM page
JOIN page_lang ON page.id = page_lang.id_page
JOIN relation ON page.id = relation.from_id
JOIN page_lang as category ON category.id_page = relation.to_id
WHERE page.type = 'blog-detail'
AND relation.type = 1

This return duplicate rows when one page have two or more categories

ID PAGE | TITLE | CATEGORIES
1 | Title 1 | category 1
2 | Title 2 | category 1
3 | Title 3 | category 2
1 | Title 1 | category 2

But I want this

ID PAGE | TITLE | CATEGORIES
1 | Title 1 | category 1, category 2
2 | Title 2 | category 1
3 | Title 3 | category 2

If I use GROUP_CONCAT(category.title) return 1 row.

You should use group_concat:

SELECT page.*, page_lang.*, group_concat(distinct category.title) as category FROM page
JOIN page_lang ON page.id = page_lang.id_page
JOIN relation ON page.id = relation.from_id
JOIN page_lang as category ON category.id_page = relation.to_id
WHERE page.type = 'blog-detail'
AND relation.type = 1
GROUP BY page.id

try using the command "UNIQUE"

SELECT UNIQUE page.*, page_lang.*, category.title as category FROM page
JOIN page_lang ON page.id = page_lang.id_page
JOIN relation ON page.id = relation.from_id
JOIN page_lang as category ON category.id_page = relation.to_id
WHERE page.type = 'blog-detail'
AND relation.type = 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM