getting values which dont exist in mysql table

前端 未结 3 1150
别那么骄傲
别那么骄傲 2021-01-20 22:29

I have a set of values(keys), 1,2,3,4,5 and following table:

id key
------
1  2
2  8
3  4

If I need to check which of the given keys are in

相关标签:
3条回答
  • 2021-01-20 23:04

    While this is a very messy solution it does work:

    select v.val from
    (
      select 1 as val
      union
      select 2 as val
      union
      select 3 as val
      union
      select 4 as val
      union
      select 5 as val
    ) v
    WHERE
    v.val NOT IN(
      SELECT `key` 
      FROM mytable 
      WHERE key IN (1,2,3,4,5)
    );
    
    0 讨论(0)
  • 2021-01-20 23:10

    This is a bit clunky, but it does work:

    select sq.val
    from   mytable t
           right join (select 1 as val
                       union 
                       select 2
                       union 
                       select 3
                       union 
                       select 4
                       union 
                       select 5 ) as sq
     on t.col = sq.val
     where t.id is null;
    

    Obligatory SQL Fiddle.

    0 讨论(0)
  • 2021-01-20 23:23

    Create temporary table with your keys:

    CREATE TEMPORARY TABLE mykeys (`key` INT);
    INSERT INTO mykeys VALUES (1),(2),(3),(4),(5);
    

    Then use NOT IN:

    SELECT `key`
    FROM mykeys
    WHERE `key` NOT IN (SELECT `key` FROM mytable)
    

    Finally, drop your TEMP table if you must:

    DROP TABLE mykeys
    

    EDIT: Added SQLFiddle.


    If you are using PostgreSQL which supports EXCEPT operator, and also VALUES statement can be used to create row set from list of values, there is another, easier way to do this without temporary tables (SQLFiddle):

    VALUES (1),(2),(3),(4),(5)
    EXCEPT
    SELECT key FROM mytable
    
    0 讨论(0)
提交回复
热议问题