2015-08-28 66 views
0

有2個表T1和T2 sql是否有任何變體在T2關聯行不存在的情況下從T1中選擇所有行?沒有JoinLeftSQL選擇連接表中的行是否爲空

例如

table user 
id---name 
1  A 
2  B 

task 
id----idUser 
1  1 

結果== 2,B BR!

+0

什麼是不使用Leftjoin的原因是什麼?你可以通過左加入輕鬆實現這一點 –

+0

我認爲這個查詢不會工作,當你有不同的用戶名的第一個表中有多個記錄的id = 2 –

回答

1

的典型方法是使用not in

select u.* 
from user u 
where u.id not in (select iduser from task); 

然而,not exists具有更好的語義,因爲它處理NULL值更直觀:

select u.* 
from user u 
where not exists (select 1 from task t where t.iduser = u.id);