首页 > 解决方案 > 哪个sql查询是正确的

问题描述

我有一张带员工的表 A,其中 id-primary key,boss_id - foreign id。我想撤回没有雇员的雇主。哪个查询是正确的?

select a1.* 
from A a1 
inner join A a2 on a1.id = a2.boss_id 
where a2.id is null

select a1.* 
from A a1 
left join A a2 on a1.id = a2.boss_id 
where a2.id is null

select a1.* 
from A a1 
inner join A a2 on a1.boss_id = a2.id 
where a2.id is null

select a1.* 
from A a1 
left join A a2 on a1.boss_id = a2.id 
where a2.id is null

或者每一个都不正确

标签: sql

解决方案


为什么不直接not exists?所有记录都来自A a1哪里a1是无人老板:

select a1.*
  from A a1 where not exists (select 1 
                                from A a2
                               where a2.boss_id = a1.id)

推荐阅读