问题
For simplification, I have two tables related with one to many using a foreign key, for example:
Users table:
id
name
Actions table:
id
user_id
one user may have many actions or not. I need an sql select that returns users ids that don't have a user_id value in the actions table.
Users Table:
id name
1 John
2 Smith
3 Alice
Actions Table:
id user_id
1 3
2 1
So I need an sql query that returns the user id 2 (Smith) because the foreign key values don't include the id 2
I tried the following SQL, but it returns all users ids:
SELECT users.id from users left join actions on actions.user_id is null
回答1:
select u.id
from users u
left outer join actions a on a.user_id = u.id
where a.user_id is null
回答2:
Optimized version would be:
SELECT u.id
FROM users u
LEFT JOIN actions a
ON a.user_id = u.id
AND ISNULL(a.user_id)
回答3:
SELECT u.id
FROM users u
LEFT JOIN actions a
ON a.user_id = u.id
WHERE a.user_id IS NULL
来源:https://stackoverflow.com/questions/13108587/selecting-primary-keys-that-do-not-have-foreign-keys-in-another-table