Concat专栏MYSQL

时间:2016-11-16 08:17:01

标签: mysql concat group-concat

我有这个选择

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

当一个页面有两个或更多类别

时,返回重复的行

ID PAGE |标题|类别
1 |标题1 |第1类
2 |标题2 |第1类
3 |标题3 |第2类
1 |标题1 |第2类

但我想要这个

ID PAGE |标题|类别
1 |标题1 |第1类,第2类
2 |标题2 |第1类
3 |标题3 |第2类

如果我使用GROUP_CONCAT(category.title)返回1行。

2 个答案:

答案 0 :(得分:1)

你应该使用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

答案 1 :(得分:0)

尝试使用命令" 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