简体   繁体   English

MySQL-“子查询返回多于1行”错误

[英]Mysql - “subquery returns more than 1 row” error

I have two tables : 我有两个表:

ingredients 配料

|   id   |       iName      |
-----------------------------
|   101  |     Curcumin     |
|   102  |     Riboflavin   |
|   103  |     Protease     |
|   104  |    Tartrazine    |
|   105  |      Amylase     |

foodproduct_ingredient foodproduct_ingredient

|  foodproduct_id  |  ingredient_id   |
---------------------------------------
|         1        |        101       |
|         1        |        102       |
|         1        |        104       |

And I just want to get list iName for every single foodproduct. 我只想获取每种食品的清单iName。 For example, when I want to get iName in foodproducts.id = 1 must be 例如,当我想在foodproducts.id = 1中获取iName时

|        iName       |
----------------------
|      Curcumin      |
|      Riboflavin    |
|      Tartrazine    |

I have tried to insert query : 我试图插入查询:

SELECT ingredients.iName FROM ingredients INNER JOIN foodproduct_ingredient 
        ON ingredients.id = foodproduct_ingredient.foodProduct_id 
        WHERE ingredients.id = 
        (SELECT foodproduct_ingredient.ingredient_id FROM foodproduct_ingredient INNER JOIN foodproducts 
        ON foodproducts.id = foodproduct_ingredient.foodProduct_id 
        WHERE foodproducts.id = 1)

but it returns subquery returns more than 1 row 但它返回子查询返回的行多于1

Can somebody help me? 有人可以帮我吗? Thanks :) 谢谢 :)

*Note : there is table foodproducts just for join to get id of foodproducts *注:有一些餐桌食品仅供加入,以获取食品的ID

I think you should use IN clause 我认为您应该使用IN子句

SELECT ingredients.iName FROM ingredients INNER JOIN foodproduct_ingredient 
    ON ingredients.id = foodproduct_ingredient.foodProduct_id 
    WHERE ingredients.id In 
    (SELECT foodproduct_ingredient.ingredient_id FROM foodproduct_ingredient INNER JOIN foodproducts 
    ON foodproducts.id = foodproduct_ingredient.foodProduct_id 
    WHERE foodproducts.id = 1)

By the way you wont even need subquery i guess. 顺便说一句,我猜你甚至不需要子查询。 Try to use below query 尝试使用以下查询

select i.iName from ingredients i
join foodproduct_ingredient fi
on fi.ingredient_id = i.id
where fi.foodproduct_id = 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM