'MYSQL QUERY: Can you use IN with 2 different fields?
My database has 2 tables. One table with customers and products and another table that links them:
Table 1: objects (id,name,id_type) where id_type is the type of object (1 client, 2 product)
Table 2: object_relations (id,id_child,id_parent) where id_child and id_parent are objects.id.
My initial query shows you specific clients that have bought specific products. The products and clients are shown at the following example:
SELECT o.*
FROM objects AS o
LEFT JOIN objects_relations AS o_r ON(o_r.id_child = o.id)
WHERE o.type=1
AND EXISTS (
SELECT
FROM objects AS o9
LEFT JOIN objects_relations AS o_r9 ON (o_r9.id_child = o9.id)
WHERE o9.id=o.id
AND o_r9.id_parent=o_r.id_parent
AND (
(o9.id=21 AND o_r9.id_parent=3)
OR (o9.id=21 AND o_r9.id_parent=5)
OR (o9.id=25 AND o_r9.id_parent=2)
OR (o9.id=25 AND o_r9.id_parent=7)
OR ...long list
)
)
I'd love to see another way to implement the long list of specific product and clients, like a IN (). Is there a better way?
Solution 1:[1]
You can use nested lists with IN
AND (o9.id, o_r9.id_parent) in ((21, 3), (21, 5), (25, 2), (25, 7))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barmar |
