简体   繁体   English

通过带有索引的多列进行SQL过滤

[英]SQL filtering by multiple columns with indexes

I'd like to expand a question I posted a while ago : 我想扩展一下我之前发布的问题

I'm querying a table for rows in which pairs of columns are in a specific set. 我正在查询表中的行,其中成对的列在特定的集合中。 For example, consider the following table: 例如,考虑下表:

id | f1  | f2
    -------------
    1  | 'a' | 20
    2  | 'b' | 20
    3  | 'a' | 30
    4  | 'b' | 20
    5  | 'c' | 20

And I wish to extract rows in which the pair (f1, f2) are in a specified set of pairs, eg (('a',30), ('b', 20),...). 我希望提取其中(f1,f2)对位于指定对对中的行,例如((''a',30),('b',20),...)。 In the original question, Mark answered correctly that I can use the following syntax: 在原始问题中, 马克回答正确,我可以使用以下语法:

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

This works fine, but I see some unexpected behavior regarding indexes: 这可以正常工作,但是我发现一些有关索引的意外行为:
I've defined a multi-column index for f1, f2, named IndexF1F2 . 我为f1和f2定义了一个多列索引,名为IndexF1F2 Using the EXPLAIN phrase, I see that MySql uses the index for a single comparison, eg: 使用EXPLAIN短语,我看到MySql使用索引进行单个比较,例如:

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

but not when using the 'IN' clause, as in the example above. 但在使用“ IN”子句时则不能,如上例所示。 Giving hints, eg USE INDEX(IndexF1F2) or even FORCE INDEX(IndexF1F2) , does not seem to make any difference. 提供提示,例如USE INDEX(IndexF1F2)甚至FORCE INDEX(IndexF1F2)似乎没有任何区别。

Any ideas? 有任何想法吗?

This is a known bug in MySQL . 这是MySQL一个已知错误

Use this syntax: 使用以下语法:

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

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

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