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

前端 未结 3 1499
囚心锁ツ
囚心锁ツ 2021-02-05 19:53

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
<
相关标签:
3条回答
  • 2021-02-05 20:21
    SELECT u.id
    FROM users u
    LEFT JOIN actions a
       ON a.user_id = u.id
    WHERE a.user_id IS NULL
    
    0 讨论(0)
  • 2021-02-05 20:29

    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)
    
    0 讨论(0)
  • 2021-02-05 20:30
    select u.id
    from users u
    left outer join actions a on a.user_id = u.id
    where a.user_id is null
    
    0 讨论(0)
提交回复
热议问题