MySQL子查询不受限制

时间:2015-06-07 00:13:16

标签: mysql

我有一张看起来像这样的表

-----------------------------------------
ID |    Food          | Maker           |
----------------------------------------
1  |   Burrito        | Chiptole        |
-------------------------------
2  |   Burrito        | FreeBirds       |
----------------------------------
3  |   Taco           | Chiptole        |
--------------------------------------
4  |   Taco           | Taco Bell       |
--------------------------------------
5  |   Taco           | Torchy's Taco's |

我想检索我的IN子句中指定的所有食物制作者('burrito'),但我也想知道还有谁制作这种食物。

我的结果应该包含。

    Food    | Maker    | Maker List 
----------------------------------------------
1.  Burrito | Chiptole | Chiptole,Freebirds
--------------------------------------------
2.  Taco    | Chiptole | Chiptole,Taco Bell,Torchy's Taco's

Maker必须始终保留我指定的条目。我的查询返回给我这个列表,但它将Maker改为为该条目检索的最后一行:

 SELECT ID,Food,Maker, GROUP_CONCAT(c.Maker) as Maker List
 FROM (Suppliers s) 
 WHERE Food
 IN (SELECT DISTINCT Food FROM Suppliers WHERE Maker IN ('Chiptole')) 

我的结果:这是错误的

 Food       | Maker           | Maker List 
----------------------------------------------
1.  Burrito | FreeBirds       | Chiptole,Freebirds
--------------------------------------------
2.  Taco    | Torchy's Taco's | Chiptole,Taco Bell,Torchy's Taco's

2 个答案:

答案 0 :(得分:1)

怎么样:

SELECT ID, Food, (
  SELECT s2.Maker FROM Suppliers s2
  WHERE s2.Food = s1.Food ORDER BY s2.ID ASC LIMIT 1
) AS Maker, GROUP_CONCAT(s1.Maker) AS Maker_List FROM Suppliers s1;

我不确定你究竟要求的是什么,所以请随时提供建议,我会尝试编辑。

答案 1 :(得分:1)

您可以使用GROUP_CONCAT()尝试以下内容。 See a demo fiddle here

select ID, 
MIN(Maker) as Maker,
GROUP_CONCAT(Maker) as `Maker List`
FROM food_table
GROUP BY Food;

结果:

enter image description here

不确定我是否真的了解您,但我认为您希望将Maker作为手动输入列。如果是,那么您可以修改您的查询,如

select ID, 
'FreeBirds' as Maker,
GROUP_CONCAT(Maker) as `Maker List`
FROM food_table
GROUP BY Food;