gpt4 book ai didi

mysql - SQL - 将多对多桥接表转换为一对一表

转载 作者:行者123 更新时间:2023-11-29 19:05:59 24 4
gpt4 key购买 nike

我正在努力编写一个查询来从这样的表中获取数据:

id    food_id    ingre_id
1 1 13
2 1 9
3 2 13
4 3 5
5 4 9
6 4 10
7 5 5

假设在该表中,每个 food 只有 1 或 2 个 ingre id。然后我想要一个像这样的表:

item_id    ingre1_id    ingre2_id
1 13 9
2 13 null //any food that have 1 ingre then set ingre2_id to null
3 5 null
4 9 10
5 5 null

请建议我执行此类转换的查询。谢谢!

最佳答案

您可以使用聚合。如果您不关心行内的顺序:

select food_id, min(ingred_id) as ingred1_id,
(case when min(ingred_id) <> max(ingred_id) then max(ingred_id) end) as ingred2_id
from t
group by food_id;

注意:使用 min()/max() 是特别有效的,因为您有两个值。如果您有更多值,请使用适当的数据提出另一个问题。

关于mysql - SQL - 将多对多桥接表转换为一对一表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43501640/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com