You could solve this by creating a temporary table with the searched values and do a LEFT JOIN with the system table searching for NULL in comparison. But it would have some simpler way to return the missing values?
In my opinion, the temporary table is the simplest output. An alternative is to use a lot of UNION
, but it looks pretty ugly:
SELECT id FROM
(SELECT 1 AS id UNION SELECT 23 AS id UNION SELECT 45 AS id /* etc */) tbl
WHERE id NOT IN (SELECT id FROM tabela)
Demo in http://sqlfiddle.com/#! 2/812b5/12
You can also use an interesting trick described in this answer of Bacchus to the question How to generate numerical sequences in SQL without creating tables? The idea is to keep an integer table in your bank, with 10 rows (the numbers from 0 to 9):
CREATE TABLE inteiros (i INT);
INSERT INTO inteiros (i) VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);
With this table you can simulate a generator, since Mysql does not support native generators. For example, you can generate numbers from 1 to 1000 like this:
SELECT d3.i*100+d2.i*10+d1.i+1 AS gerador
FROM inteiros AS d1
JOIN inteiros AS d2
JOIN inteiros AS d3;
Applying this to your example, and considering that the ids to be checked are in this range from 0 to 1000, the following query generates the list:
SELECT d3.i*100+d2.i*10+d1.i+1 AS gerador
FROM inteiros AS d1
JOIN inteiros AS d2
JOIN inteiros AS d3
HAVING gerador IN (1,23,45,68,91,126,345,418,509,610);
Finally, using this to get the result you want:
SELECT id FROM (
SELECT d3.i*100+d2.i*10+d1.i+1 AS id
FROM inteiros AS d1
JOIN inteiros AS d2
JOIN inteiros AS d3
HAVING gerador IN (1,23,45,68,91,126,345,418,509,610);
) tbl
WHERE id NOT IN (SELECT id FROM tabela)
That’s a good question. However, if you are doing this in some programming language (Java, PHP, C#) it would be simpler to retrieve the existing Ids in a vector and make a diff of the result with the original ID vector.
– utluiz