MySQL - Group_concat querywithout group

时间:2016-09-26 08:38:39

标签: mysql

我有3个表:design,category和design_category

我需要,每个设计都有不同类别的行,但是有一个带有concat类别的列。我做下一个:

SELECT d.id, d.name, c.id, GROUP_CONCAT(c.id)
FROM design d
LEFT JOIN design_category dc ON dc.design_id = d.id 
LEFT JOIN category c ON dc.category_id = c.id  
GROUP BY d.id


+----+-----------------------------------+------+--------------------+
| id | name                              | id   | GROUP_CONCAT(c.id) |
+----+-----------------------------------+------+--------------------+
|  2 | Design 1                          |  177 | 177,178            |
|  4 | Design 2                          |  179 | 179,177,178        |
|  5 | Design 3                          |  177 | 177,178            |
|  6 | Design 4                          |  177 | 177,178            |
|  7 | Design 5                          |  177 | 177,178            |
|  8 | Design 6                          |  181 | 181,180            |
+----+-----------------------------------+------+--------------------+

但我不会那样:

+----+-----------------------------------+------+--------------------+
| id | name                              | id   | GROUP_CONCAT(c.id) |
+----+-----------------------------------+------+--------------------+
|  2 | Design 1                          |  177 | 177,178            |
|  2 | Design 1                          |  178 | 177,178            |
|  4 | Design 2                          |  177 | 179,177,178        |
|  4 | Design 2                          |  178 | 179,177,178        |
|  4 | Design 2                          |  179 | 179,177,178        |
|  5 | Design 3                          |  177 | 177,178            |
|  5 | Design 3                          |  178 | 177,178            |
|  6 | Design 4                          |  177 | 177,178            |
|  6 | Design 4                          |  178 | 177,178            |
|  7 | Design 5                          |  177 | 177,178            |
|  7 | Design 5                          |  178 | 177,178            |
|  8 | Design 6                          |  180 | 181,180            |
|  8 | Design 6                          |  181 | 181,180            |
+----+-----------------------------------+------+--------------------+

在MySQL可能吗?

1 个答案:

答案 0 :(得分:1)

这应该有效:

select x.id, x.name, y.id, z.grouped_id from FROM design x
LEFT JOIN design_category xy ON xy.design_id = x.id 
LEFT JOIN category y ON xy.category_id = y.id  
left join(
SELECT d.id id , GROUP_CONCAT(c.id) grouped_id
FROM design d
LEFT JOIN design_category dc ON dc.design_id = d.id 
LEFT JOIN category c ON dc.category_id = c.id  
GROUP BY d.id) zon z.id= x.id