简体   繁体   English

多列SQL过滤

[英]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. 我有一个MySQL表,我想查询其列是一组特定的行。 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. 现在,我希望提取其中对(f1,f2)为('a',30)或('b',20)的行,即行2,3,4。 I also wish to do it using an 'IN' style filter, as I may have many pairs to fetch. 我也希望使用'IN'样式过滤器,因为我可能有很多对要获取。 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子句中为f1和f2指定的值的笛卡尔乘积,即f1 ='a'或'b'和f2 = 30,20的所有可能组合的行,因此也选择了行1。

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 :-) 只有有效的SQL语法:-)

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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