gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 00:31:27 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com