gpt4 book ai didi

mysql - 实现并查询引用两个表的MYSQL外键

转载 作者:行者123 更新时间:2023-11-29 07:25:39 25 4
gpt4 key购买 nike

我有两个表酒店事件

Hotels
id | name |
1 | hilton |
2 | taj samudra |
3 | galadari |


Activities
id | name |
1 | air balloon |
2 | whale watching |
3 | jungle safari |

我还有一张 table Tour

id      | starting_location_id | starting_location_type 
1 | 1 | hotel
2 | 1 | activity

用户可以从酒店或事件开始游览。

我想要的是传递id并且需要像这样使用join获取数据

id   | name
1 | hitlon
2 | air baloon

如果我以后解释,我想要一个可以引用多个表的外键。注意:- 这还没有实现。我想实现这种场景。我想在 Tour 表中传递 id 并需要获取该记录的关联数据。

这在 MYSQL 中可能吗?

最佳答案

您可以尝试以下 -

DEMO

select t1.id,coalesce(h.name,a.name) as name 
from tour t1
left join hotels h on t1.starting_location_id=h.id and starting_location_type='hotel'
left join Activities a on t1.starting_location_id=a.id and starting_location_type='activity'

OUTPUT:

id name
2 air balloon
1 hilton

关于mysql - 实现并查询引用两个表的MYSQL外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53956217/

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