我有以下两个表:
table1
id
name
ownedby
table2
id
ownername
这里,在table1中,ownby可以是0(表示它不归任何人所有)或引用table2的id列。现在我想要的是从table1获取数据,但如果owenedby> 0
从table2获取所有者名称输出基本上是:
1 0 ==>owned by no one
2 Barka =======> owned by barka
答案 0 :(得分:1)
以下查询应该有效(尽管我没有测试过):
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;
希望它有所帮助!