SELECT that returns list of values not occurring in any row

后端 未结 6 1576
星月不相逢
星月不相逢 2020-12-14 06:02

Query:

select id from users where id in (1,2,3,4,5)

If the users table contains ids 1, 2, 3, this would return 1, 2, and 3. I want a query

6条回答
  •  星月不相逢
    2020-12-14 07:00

    If you don't want to (explicitly) use temporary tables, this will work:

    SELECT id FROM (
      (SELECT 1 AS id) UNION ALL
      (SELECT 2 AS id) UNION ALL
      (SELECT 3 AS id) UNION ALL
      (SELECT 4 AS id) UNION ALL
      (SELECT 5 AS id)
    ) AS list
    LEFT JOIN users USING (id)
    WHERE users.id IS NULL
    

    However, it is quite ugly, quite long, and I am dubious about how it would perform if the list of IDs is long.

提交回复
热议问题