Selecting primary keys that do not have foreign keys in another table

北城余情 提交于 2019-12-04 11:21:58

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!