I have composite index for example INDEX name (x,y)
. Where x and y - integer. Why it don't work with the next query:
select * from t
where (x, y) in ((1, 1), (2, 2))
Result of Explain: using where, file sort
答案 0 :(得分:0)
Depends what version of MySQL you use. Optimizing range comparisons for row constructors like the example you show was implemented in MySQL 5.7.
In MySQL 5.6 or earlier versions, this query would produce a result, but could not use an index to improve performance. It would do a table-scan.
https://dev.mysql.com/doc/refman/5.7/en/range-optimization.html#row-constructor-range-optimization
Re your comment confirming that you're using MySQL 5.6:
The workaround for MySQL 5.6 to make sure it uses the index:
select * from t where x=1 and y=1
union all
select * from t where x=2 and y=2
You'll need an additional union for each element in your IN()
list.
This might be a good justification to upgrade to MySQL 5.7. For what it's worth, MySQL 5.7 has been GA since 2015-10-21 (27 months ago), and it has had 11 subsequent GA releases since then. It's pretty stable and reliable now.
答案 1 :(得分:0)
您可以尝试将查询从where (x, y) in ((i1, j1), (i2, j2),(i3,j3),....
更改为where x in (i1,i2,i3....) and y in (j1,j2,j3,....)
它通常适用于mysql 5.6和索引使用。但元素的数量" i"必须与" j"相同。它将获得与x=i1 and y=j1 union all
相同的结果,但不会与所有查询相同。并且必须订购i1,j1,i2,j2,i3,j3 ......试试这个。