Search code examples
phpmysqlwhere-in

Is there a way to retrieve only the values in the IN (or NOT IN) clause that did not match a record in a table?


This might be a weird question. Currently, I have a table with a bunch of data in it. Using PHP, I am dynamically creating the IN clause.

SELECT * FROM table
WHERE field IN ('str1', 'str2', [...])

Let's say no records matched with 'str1' or 'str2', is there a way to retrieve 'str1' and 'str2'?


Solution

  • SELECT dmy.id
    FROM (
       SELECT 'str1' as id
       UNION ALL
       SELECT 'str2' 
       UNION ALL
       .....
    ) dmy
    LEFT JOIN some_table ON some_table.field = dmy.id
    WHERE some_table.field IS NULL
    

    On special request, here is an explanation:

    The derived table (the inner select) just creates a "dummy" table that contains all the desired values. Then this dummy table is outer joined to the real table. Anything that has no value (NULL) in the outer joined table (some_table) does not exist in the list of values from the dummy "table".

    To see the effect of the derived table just run it stand alone without the join:

    SELECT dmy.id
    FROM (
       SELECT 'str1' as id
       UNION ALL
       SELECT 'str2' 
       UNION ALL
       .....
    ) dmy