选择另一个表中没有外键的主键 [英] Selecting primary keys that do not have foreign keys in another table

查看:90
本文介绍了选择另一个表中没有外键的主键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为简单起见,我有两个使用外键一对多关联的表,例如:

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

一个用户可能有很多动作或没有很多动作.我需要一个SQL select来返回在操作表中没有user_id值的用户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

所以我需要一个返回用户ID 2(Smith)的SQL查询,因为外键值不包括ID 2

So I need an sql query that returns the user id 2 (Smith) because the foreign key values don't include the id 2

我尝试了以下SQL,但它返回了所有用户ID:

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

推荐答案

select u.id
from users u
left outer join actions a on a.user_id = u.id
where a.user_id is null

这篇关于选择另一个表中没有外键的主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆