gpt4 book ai didi

mysql - MySQL根据table1中的值从table2中不相关的表中获取记录

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

我有以下两个表:

       table1
id
name
ownedby


table2
id
ownername

这里,在table1中,ownedby可以为0(表示它不被任何人拥有)或引用table2的id列。现在我想要的是从 table1 获取数据,但如果owenedby>0

,则从 table2 获取所有者名称

输出基本上是:

     1  0 ==>owned by no one
2 Barka =======> owned by barka

最佳答案

以下查询应该有效(尽管我没有测试它):

select t1.id, t1.name,
(case when t1.ownedby = 0 then 'No one'
else t2.ownername
end) as Ownername
from table t1
Left Join table t2
on t1.ownedby = t2.id
group by t1.id;

希望对你有帮助!

关于mysql - MySQL根据table1中的值从table2中不相关的表中获取记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46911983/

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