Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select values that are NOT in table

Let's say I have three values in PHP: "a", "b", "c". Doesn't matter whether in an array or comma separated string.
There is a table in database:

id | value  
1  | a  
2  | b  
3  | d  

My purpose is to find the values that are in php array but not in database table.
The given example will give "c".
Can I do it with only one query?

UPDATE

Received several good suggestions in answers about array_diff(), though in my case the DB table is really large and the array has not more than 5-6 items. So it would be better to perform 5-6 queries, I think.

like image 619
lvil Avatar asked Jan 20 '26 22:01

lvil


1 Answers

If the PHP array is short, you can build a UNION ALL query to build your small table, then use NOT IN or LEFT JOIN query (whichever is faster) against the large table:

SELECT value
FROM (
    SELECT 'a' AS value
    UNION ALL
    SELECT 'b'
    UNION ALL
    SELECT 'c'
) AS php_array_values
WHERE value NOT IN (
    SELECT value
    FROM that_large_table
);

Alternately, you can insert the php array values in a temporary table and use the IN or JOIN queries. Of course, this means you end up writing three extra queries:

CREATE TEMPORARY TABLE IF NOT EXISTS php_array_values (value VARCHAR(100));

DELETE FROM php_array_values;

INSERT INTO php_array_values VALUES ('a'), ('b'), ('c');

SELECT php_array_values.value
FROM php_array_values
LEFT JOIN that_large_table ON php_array_values.value = that_large_table.value
WHERE that_large_table.value IS NULL
like image 95
Salman A Avatar answered Jan 22 '26 12:01

Salman A