简体   繁体   中英

SQL filtering by multiple columns

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, ie 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:

SELECT * FROM my_table
WHERE (f1, f2) = ('a', 30)
OR    (f1, f2) = ('b', 20)

Or using a join:

SELECT *
FROM my_table T1
(
    SELECT 'a' AS f1, 30 AS f2
    UNION ALL
    SELECT 'b', 20
) T2
ON T1.f1 = T2.f1 AND T1.f2 = T2.f2
SELECT * FROM my_table WHERE (f1= 'a' AND f2=30) OR (f1='b' AND f2=20);

A rough but practical way is to use string concatenation:

SELECT *
FROM MyTable
WHERE CONCAT(f1, '_', f2) IN ('a_30', 'b_20')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM