I have the following query:
SELECT question_code FROM table_questions WHERE question_code IN (1,2,3,111,222);
Here, values (1,2,3,111,222) are coming from PHP array.
The output for the above query is:
question_code
1
2
3
I want the output to be the question_codes which are not in the table and present in the Array.
i.e. I want the output to be question_code which do not exist in the table.
question_code
111
222
I know this problem can be handled in PHP after retrieving the data from the Table. But as I may have large number of tuples, solution which can take care of this thing at query level would be helpful.
You will get the record of SELECT question_code FROM table_questions WHERE question_code IN (1,2,3,111,222);
in array and values (1,2,3,111,222)
are coming from PHP array.
Use array_diff
to compare two arrays and gets the difference. For reference http://www.w3schools.com/php/func_array_diff.asp
If you want to use plain SQL you have to use a LEFT JOIN:
SELECT c.question_code
FROM (SELECT 1 AS question_code
UNION ALL select 2
UNION ALL SELECT 3
UNION ALL SELECT 111
UNION ALL SELECT 222) AS c
LEFT JOIN table_questions q
ON c.question_code = q.question_code
WHERE
q.question_code IS NULL
you can create the subquery SELECT .. UNION ALL ..
dynamically, like this:
<?php
$ids = array(1,2,3);
$subquery = str_repeat('SELECT ? AS q UNION ALL ', count($ids) - 1) . 'SELECT ? AS q';
$sql = <<<SQL
SELECT c.q FROM ($subquery) AS c
LEFT JOIN table_questions q
ON c.q = q.question_code
WHERE
q.question_code IS NULL
SQL;
$stm = $db->prepare($sql);
$stm->execute($ids);
$data = $stm->fetchAll();
?>
but it might not be too pratical... the only alternative is to process the returned question_codes
codes in php.