2012-10-28 65 views
7

爲了簡化起見,我必須使用外鍵與一個與許多兩張表,例如:選擇沒有在其它表的外鍵主鍵

Users table: 
id 
name 

Actions table: 
id 
user_id 

一個用戶可以有許多行動或不。我需要一個sql select,它返回操作表中沒有user_id值的用戶id。

Users Table: 
id  name 
1  John 
2  Smith 
3  Alice 

Actions Table: 
id  user_id 
1  3 
2  1 

所以我需要一個SQL查詢,返回用戶ID 2(史密斯),因爲外鍵的值不包括ID 2

我嘗試以下SQL,但是它返回所有用戶的id :

SELECT users.id from users left join actions on actions.user_id is null 

回答

11
select u.id 
from users u 
left outer join actions a on a.user_id = u.id 
where a.user_id is null 
2
SELECT u.id 
FROM users u 
LEFT JOIN actions a 
    ON a.user_id = u.id 
WHERE a.user_id IS NULL 
+0

它沒有返回任何結果。 – SaidbakR

+0

是的,在我的查詢中有一個錯字。 – bobwienholt

4

優化的版本是:

SELECT u.id 
FROM users u 
LEFT JOIN actions a 
ON a.user_id = u.id 
AND ISNULL(a.user_id) 
+0

它返回所有用戶。 – SaidbakR

+0

你是對的我有一個錯過類型正確的是:ON a.user_id = u.id – ChaosClown