SELECT that returns list of values not occurring in any row

后端 未结 6 1577
星月不相逢
星月不相逢 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条回答
  •  猫巷女王i
    2020-12-14 06:33

    A different option is to use another table containing all possible ids and then do a select from there:

    mysql> describe ids;
    +-------+-----------------+------+-----+---------+-------+
    | Field | Type            | Null | Key | Default | Extra |
    +-------+-----------------+------+-----+---------+-------+
    | id    | int(5) unsigned | NO   |     | 0       |       |
    +-------+-----------------+------+-----+---------+-------+
    1 row in set (0.05 sec)
    
    mysql> select * from ids;
    +----+
    | id |
    +----+
    |  1 |
    |  2 |
    |  3 |
    |  4 |
    |  5 |
    +----+
    5 rows in set (0.00 sec)
    
    mysql> select * from users;
    +----+
    | id |
    +----+
    |  1 |
    |  2 |
    |  3 |
    +----+
    3 rows in set (0.00 sec)
    
    
    mysql> select id from ids where id not in (select id from users);
    +----+
    | id |
    +----+
    |  4 |
    |  5 |
    +----+
    2 rows in set (0.04 sec)
    

    Added side effect - allows you to expand the result list by inserting into the ids table

提交回复
热议问题