mysql - 选择另一个表中没有外键的主键

标签 mysql sql database one-to-many

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

Users table:
id
name

Actions table:
id
user_id

一个用户可能有很多 Action ,也可能没有。我需要一个 sql select,它返回在操作表中没有 user_id 值的用户 ID。

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

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

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

关于mysql - 选择另一个表中没有外键的主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13108587/

相关文章:

sql - Illuminate\Support\Fluent 类的对象无法转换为 int

php - 获取所有选中复选框的值并将它们插入数据库 - PHP

mysql - 所有记录的空值

php - 使用 Codeigniter 的数据库响应中的 "Nested"数组

sql - 授予对 View 的 SELECT 权限,但不授予对基础对象的 SELECT 权限

mysql - 使用 OR 和 NAND 选择查询

database - 我应该为此使用多个 PostgreSQL 查询吗?

php - 分页在 Laravel 4 中不起作用

c# - FileStream 错误 - 进程无法访问文件...被另一个进程使用

sql - 有没有办法在没有公共(public)列的情况下连接两个查询