I’ve got a product table with some kind of extra key, values used for analytics and stuff. My problem is that if it’s easy to find the product with the specified key, it’s much more tricky to find the one without the key. Let’s cut the talk and show the code.
SELECT products.*
FROM products
JOIN metas ON products.id = metas.product_id
WHERE
metas.key = 'mykey' AND
metas.value = '1'
I’ll get all the products with the mykey key specified and set to the value 1 (the 1 in the example below).
Now I’d like to get all the products without the key mykey set (the 2 in the example below). No elements exist in the metas table if the key isn’t set.
+-------------+ +----------------------------+
| products | | metas |
+=============+ +============+=======+=======+
|id | | product_id | key | value |
+-------------+ +------------+-------+-------+
| 1 | | 1 | mykey | 1 |
| 2 | | 1 | foo | bar |
+-------------+ +------------+-------+-------+
Extra points if no sub-select are hurt in the process.
Using
NOT EXISTSwould be an option.