MySQL multiple columns in IN clause

人盡茶涼 提交于 2019-11-28 02:47:29

问题


I have a database with four columns corresponding to the geographical coordinates x,y for the start and end position. The columns are:

  • x0
  • y0
  • x1
  • y1

I have an index for these four columns with the sequence x0, y0, x1, y1.

I have a list of about a hundred combination of geographical pairs. How would I go about querying this data efficiently?

I would like to do something like this as suggested on this SO answer but it only works for Oracle database, not MySQL:

SELECT * FROM my_table WHERE (x0, y0, x1, y1) IN ((4, 3, 5, 6), ... ,(9, 3, 2, 1));

I was thinking it might be possible to do something with the index? What would be the best approach (ie: fastest query)? Thanks for your help!

Notes:

  • I cannot change the schema of the database
  • I have about 100'000'000 rows

EDIT: The code as-is was actually working, however it was extremely slow and did not take advantage of the index (as we have an older version of MySQL v5.6.27).


回答1:


To make effective use of the index, you could rewrite the IN predicate

(x0, y0, x1, y1) IN ((4, 3, 5, 6),(9, 3, 2, 1))

Like this:

(  ( x0 = 4 AND y0 = 3 AND x1 = 5 AND y1 = 6 ) 
OR ( x0 = 9 AND y0 = 3 AND x1 = 2 AND y1 = 1 )
)



回答2:


I do not understand your point. The following query is valid MySQL syntax:

SELECT *
FROM my_table
WHERE (x0, y0, x1, y1) IN ((4, 3, 5, 6), ... ,(9, 3, 2, 1));

I would expect MySQL to use the composite index that you have described. But, if it doesn't you could do:

SELECT *
FROM my_table
WHERE x0 = 4 AND y0 = 3 AND x1 = 5 AND y1 = 6
UNION ALL
. . .
SELECT *
FROM my_table
WHERE x0 = 9 AND y0 = 3 AND x1 = 2 AND y1 = 1

The equality comparisons in the WHERE clause will take advantage of an index.




回答3:


MySQL allows row constructor comparisons like you show, but the optimizer didn't know how to use an index to help performance until MySQL 5.7.

  • https://dev.mysql.com/doc/refman/5.7/en/row-constructor-optimization.html



回答4:


You can concatenate the four values into a string and check them like that:

SELECT * 
FROM my_table 
WHERE CONCAT_WS(',', x0, y0, x1, y1) IN ('4,3,5,6', ..., '9,3,2,1');



回答5:


The way you are doing is giving correct results in the mysql version on my machine. I am using v5.5.55. Maybe you are using an older one. Please check that.

If you still want to solve this problem in your own version or the above mentioned solution doesn't work then only read the next solution.

I am still not clear about data types and range of all your columns here. So I am assuming that data type is integer and range is between 0 to 9. If this is the case you can easily do this as given below.

select * from s1 where x0+10*x1+100*y1+1000*y2 in (4356,..., 9321);


来源:https://stackoverflow.com/questions/44706196/mysql-multiple-columns-in-in-clause

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!