What kind of index would be efficient when there is IN clause?

…衆ロ難τιáo~ 提交于 2020-01-07 02:22:21

问题


Here is my query:

DELETE FROM events WHERE type = 4 AND author_id IN (?, ?) AND post_id IN (?, ?)

And here is all my current indexes:

(id)  -- PK
(author_id, seen)
(author_id, date_time)
(type, other_id, author_id)
(comment_id, type, author_id)

Well, Should I add any new index for query above?


回答1:


I would guess an index on type would probably be the only useful one; because A IN (B, C, D) translates to A = B OR A = C OR A = D, and MySQL seems to ignore indices once it encounters an OR.

Alternatively, make/execute four copies of the query with the possible combinations of author_id and post_id; but unless it is a drastic performance issue I probably would not recommend it.




回答2:


INDEX(type, author_id)
INDEX(type, post_id)

Those have type first because it is compared = constant. Then they have one IN clause. Newer versions of MySQL will efficiently "leapfrog" ("MRR") through the IN set. I don't think they can do two INs.

The optimizer will look at statistics and choose which of those two indexes is likely to be better.

Still, it may be possible that INDEX(type, other_id, author_id) will be beneficial. What version of MySQL are you running? Can you do EXPLAIN DELETE ... to see how it is likely to perform the query? If you see "ICP" or "Index condition pushdown" or "Using index condition", that will be better. (That depends on a relatively new optimization.)



来源:https://stackoverflow.com/questions/37709117/what-kind-of-index-would-be-efficient-when-there-is-in-clause

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