Happened to reach here searching for an answer. Earlier posts are pre MySQL 8. Since MySQL has value
statement since version 8.0.19 , the question can be very elegantly solved using value
statement along with CTE
which is also available since MySQL 8.0
Step 1:
Combine CTE and value statement to create a set of rows with the values that needs to be compared to the table (here the table is foo
).
with MyValues(val) as
(
values row(2),row(4),row(5),row(6),row(7)
)
Step 2:
Outer join the CTE with the table foo
and filter the rows which has the null values from the CTE after the outer join with foo
WITH myvalues(val)
AS (VALUES ROW(2), ROW(4), ROW(5), ROW(6), ROW(7))
SELECT f.id
FROM foo f
LEFT OUTER JOIN myvalues m
ON f.id = m.val
WHERE m.val IS NULL;
Trail
mysql> WITH myvalues(val)
-> AS (VALUES ROW(2), ROW(4), ROW(5), ROW(6), ROW(7))
-> SELECT f.id
-> FROM foo f
-> LEFT OUTER JOIN myvalues m
-> ON f.id = m.val
-> WHERE m.val IS NULL;
+------+
| id |
+------+
| 1 |
| 3 |
| 8 |
| 9 |
+------+
4 rows in set (0.00 sec)
Or using IN clause
mysql> WITH myvalues(val)
-> AS (VALUES ROW(2), ROW(4), ROW(5), ROW(6), ROW(7))
-> SELECT f.id
-> FROM foo f
-> WHERE id NOT IN (SELECT val
-> FROM myvalues);
+------+
| id |
+------+
| 1 |
| 3 |
| 8 |
| 9 |
+------+
4 rows in set (0.00 sec)