【问题标题】:Selecting primary keys that do not have foreign keys in another table选择另一个表中没有外键的主键
【发布时间】:2012-10-28 11:53:34
【问题描述】:

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

Users table:
id
name

Actions table:
id
user_id

一个用户可能有很多操作,也可能没有。我需要一个 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

【问题讨论】:

    标签: mysql sql database one-to-many


    【解决方案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】:

      优化后的版本是:

      SELECT u.id
      FROM users u
      LEFT JOIN actions a
      ON a.user_id = u.id
      AND ISNULL(a.user_id)
      

      【讨论】:

      • 你说得对,我有一个错误类型,正确的是:ON a.user_id = u.id
      【解决方案3】:
      SELECT u.id
      FROM users u
      LEFT JOIN actions a
         ON a.user_id = u.id
      WHERE a.user_id IS NULL
      

      【讨论】:

      • 是的,我的查询中有错字。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-30
      • 1970-01-01
      • 2016-08-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多