I have a MySql table, which I want to query for rows in which pairs of columns are in a specific set.
For example, say my table looks like this:
id | f1 | f2
-------------
1 | 'a' | 20
2 | 'b' | 20
3 | 'a' | 30
4 | 'b' | 20
5 | 'c' | 20
Now, I wish to extract rows in which the pair (f1, f2) are either (‘a’,30) or (‘b’, 20), namely rows 2,3,4. I also wish to do it using an ‘IN’ style filter, as I may have many pairs to fetch. If I try something like:
SELECT * FROM my_table WHERE f1 IN ('a','b') AND f2 IN (30, 20)
I get the Cartesian product of the values specified for f1 and f2 in the IN clauses, i.e. the rows with all possible combinations for f1 = ‘a’ or ‘b’, and f2 = 30, 20, hence row 1 is also selected.
In short, I’m need something like:
SELECT * FROM my_table WHERE (f1,f2) IN (('a',30), ('b',20))
only with a valid SQL syntax 🙂
Any ideas?
That is valid syntax.
If you don’t like it some other alternatives are:
Or using a join: