寻找帮助编辑这个sql语句

时间:2015-03-06 06:05:02

标签: mysql

SELECT c.COLORNAME, x.COLORANTNAME 
FROM Color c LEFT JOIN Formula f ON c.COLORCODE = f.COLORCODE 
LEFT JOIN Colorant x on x.COLORANTCODE = f.COLORANTCODE;

我希望此代码返回一行中一种颜色的所有着色剂名称,但它会为颜色中的每种着色剂添加一行。有什么建议吗?

+---------------+----------------+

| COLORNAME     | COLORANTNAME   |

+---------------+----------------+

| TangierIsland | Organic Yellow |

| TangierIsland | Black Oxide    |

| TangierIsland | Red Oxide      |

| BarnRed       | Organic Yellow |

| BarnRed       | Black Oxide    |

| BarnRed       | Red Oxide      |

| BarnRed       | Titanium White |

| BarnRed       | Magenta        |

| NavajoRed     | Brown Oxide    |

| NavajoRed     | Titanium White |

| NavajoRed     | Organic Red    |

| NavajoRed     | Medium Yellow  |

| DustyMauve    | Black Oxide    |

| DustyMauve    | Medium Yellow  |

| DustyMauve    | Magenta        |

| Silver        | Phalo Blue     |

| Silver        | Raw_Umber      |

| Silver        | Magenta        |

| JPastel       | Raw_Umber      |

| JPastel       | Medium Yellow  |

| JPastel       | Magenta        |

+---------------+----------------+

^这是我的sql语句生成的输出,但我希望它看起来像这样:

TangierIsland | Organic Yellow, Black Oxide, Red Oxide

BarnRed | Organic Yellow, Black Oxide, Red Oxide, Titanium White, Magenta

NavajoRed | Brown Oxide, Titanium White, Organic red, Medium Yellow, Magenta
等等。

1 个答案:

答案 0 :(得分:2)

只需使用GROUP_CONCAT(x.COLORANTNAME)代替x.COLORANTNAME:

SELECT c.COLORNAME, GROUP_CONCAT( x.COLORANTNAME ) 
FROM Color c LEFT JOIN Formula f ON c.COLORCODE = f.COLORCODE 
LEFT JOIN Colorant x on x.COLORANTCODE = f.COLORANTCODE;

结果:

+---------------+--------------------------------------+
| COLORNAME     | GROUP_CONCAT(x.COLORANTNAME)         |
+---------------+--------------------------------------+
| TangierIsland | Organic Yellow,Black Oxide,Red Oxide |
+---------------+--------------------------------------+

您也可以设置不同的分隔符而不是逗号:

GROUP_CONCAT( x.COLORANTNAME SEPARATOR '-' )