列出表中的行,并将另一个信息与MySQL相关联

时间:2018-03-26 19:14:09

标签: mysql

假设我有3个这样的SQL表:

表水果:

|----------|------------|
| fruit_id | fruit_name |
|----------|------------|
|        1 |     Banana |
|        2 |      Apple |
|        3 |       Pear |
|----------|------------|

表颜色:

|----------|------------|
| color_id | color_name |
|----------|------------|
|       91 |     Yellow |
|       92 |      Green |
|       93 |        Red |
|----------|------------|

表关联:

|----------|----------|
| fruit_id | color_id |
|----------|----------|
|        1 |       91 |
|        1 |       92 |
|        2 |       91 |
|        2 |       92 |
|        2 |       93 |
|        3 |       93 |
|----------|----------|

如何列出水果和同事颜色如下:

|----------|----------|
| fruit_id | color_id |
|----------|----------|
|        1 |    91,92 |
|        2 | 91,92,93 |
|        3 |       93 |
|----------|----------|

我尝试了什么:

SELECT 
    fruit_id,
    GROUP_CONCAT(COALESCE(color_id, "0")) AS color_id
FROM fruits
JOIN associatives
LEFT JOIN colors
    ON FIND_IN_SET(fruit_id, color_id)
GROUP BY fruit_id

2 个答案:

答案 0 :(得分:0)

您只需查询associates表格即可获得所需的结果:

 select fruit_id, GROUP_CONCAT(color_id) as color_id 
 from associatives
 group by fruit_id
  

<强>演示:    SQLFiddle demo

答案 1 :(得分:0)

如果你的水果没有颜色,你只需LEFT JOIN。但是您的样本数据并未显示出来。无论如何,我调整了来自@Hackerman的样本以包含另一个水果来展示如何处理该案例

<强> SQL DEMO

select f.fruit_id, GROUP_CONCAT( COALESCE (a.color_id, 0) ) as color_id 
from fruits f
left join associatives a
  ON f.fruit_id = a.fruit_id
group by f.fruit_id