假设我有一张表people 和一张表pets,我想显示所有养宠物的人和所有没有宠物的人。一个人可以没有宠物,也可以有任意数量的宠物。
我可以使用 IF EXISTS,但是我必须使用两个查询:
select * from person where exists (select * from pet where person.id = pet.owner)
和
select * from person where not exists (select * from pet where person.id = pet.owner)
有没有一种方法可以将这些组合在一个查询中,这样我就可以获得一个人员数据列表和一个附加列,该列说明该人是否有宠物?我不想使用 group by 和 count,因为我不需要宠物的实际数量,只需要有宠物的信息,所以我想将上述两个查询的 EXISTS 数据合并到一个额外的 bool 值中专栏。
这有可能吗?
最佳答案
替代方案
select
p.*,
case when exists
(
select *
from pets
where personId = p.id
)
then select 1
else select 0
end
as HasPets
from person p
关于mysql - 根据其他表中存在的匹配行创建列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075971/