也许我错过了一些逻辑或一种轻松做到这一点的方法。
有一张带有颜色的表格,有些可能有0,1,2,3或更多颜色与同一colorHue
id colorName colorHue ColorNumber
----------------------------------------------------
1 Orange Og 1000
2 Pumpkin Og 1000
3 Red Rd 1001
4 Brick Rd 1001
5 Carrot Og 1000
6 Blue Blue 1002
7 Scarlet Rd 1001
我需要列出所有颜色的VIEW
和其他可能的颜色,而不显示当前行的颜色名称。
id colorName Other Colors
----------------------------------------------------
1 Orange Pumpkin,Carrot
2 Pumpkin Orange,Carrot
3 Red Brick,Scarlet
4 Brick Red,Scarlet
5 Carrot Orange,Pumpkin
6 Blue
7 Scarlet Red,Brick
我可以很容易地获得所有这些GROUP_CONCAT
,但无法弄清楚如何消除对当前行的自引用。所以我明白了:
id colorName Other Colors
----------------------------------------------------
1 Orange Orange,Pumpkin,Carrot
2 Pumpkin Orange,Pumpkin,Carrot
3 Red Red,Brick,Scarlet
4 Brick Red,Brick,Scarlet
5 Carrot Orange,Pumpkin,Carrot
6 Blue Blue
7 Scarlet Red,Brick,Scarlet
答案 0 :(得分:3)
http://sqlfiddle.com/#!9/43c122/2
SELECT colorHue,
GROUP_CONCAT(IF(colorHue=colorName,null,colorName))
FROM colors
GROUP BY colorHue
更新 http://sqlfiddle.com/#!9/43c122/8
SELECT c.*,
GROUP_CONCAT(c1.colorName)
FROM colors c
LEFT JOIN colors c1
ON c.colorHue = c1.colorHue
AND c.id != c1.id
GROUP BY c.id