Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
819 views
in Technique[技术] by (71.8m points)

mysql - SQL fixed-value IN() vs. INNER JOIN performance

In answer to this SQL question, I've encountered a statement that fixed-value IN() operator is much slower than INNER JOIN with the same content, to the point that it is better to create temporary table for the values and JOIN them. Is it true (in general, with MySQL, any other SQL engine) and if yes - why? Intuitively, IN should be faster - you're comparing the potential match with a fixed set of values, which are already in memory and in needed format, while with JOIN you'd have to consult the indexes, potentially load data from disk, and perform other operations that may be not needed with IN. Am I missing something important?

Note that unlike this question and it's many duplicates, I'm talking about IN() having fixed set of values, not subquery.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This relates to the length of the IN clause - and what is sometimes called a BUG in MySQL.

MySQL seems to have a low threshold for IN clauses, when it will swap to a TABLE/INDEX SCAN instead of collecting multiple partitions (one per IN item) and merging them.

With an INNER JOIN, it is almost always forced to use a direct row-by-row in JOIN collection, which is why it is sometimes faster

Refer to these MySQL manual pages

I could be wrong since it seems to imply that IN (constant value list) should always use a binary search on each item...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...