问题
I have a table which has about one hundred million rows, and the column 'id' is the primary key, and it is the only key in the table.
I do a query like:
SELECT id,name FROM table WHERE id IN (id1, id2, id3, id4, ..., id1000);
These 1000 ids inside "IN" are actually const integers which are pre-caculated by a program.
But Mysql spends about one minute to do the query every time. It is not slow, but it is incredibly slow. What's wrong with the clause? Thank you very much!
Table definition:
CREATE TABLE mytable
(
id mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
catid smallint(5) unsigned NOT NULL DEFAULT '0',
name char(39) NOT NULL,
originalname varchar(255) NOT NULL,
thumb varchar(255) NOT NULL DEFAULT '',
description varchar(255) NOT NULL DEFAULT '',
status tinyint(2) unsigned NOT NULL DEFAULT '1',
creationtime int(11) unsigned NOT NULL DEFAULT '0',
updatetime int(11) unsigned NOT NULL DEFAULT '0',
score int(11) unsigned NOT NULL
PRIMARY KEY (id)
)
ENGINE=MyISAM
AUTO_INCREMENT=13074618
DEFAULT CHARSET=utf8
回答1:
After the IN 'list' reaches a certain size, MySQL will swap to a TABLE/INDEX SCAN, this has the possibility of being terribly slow.
You can rewrite the query to use a TEMPORARY TABLE, or JOIN (SELECT UNION), to see if that helps performance.
Consider running EXPLAIN EXTENDED to see what slows it down.
来源:https://stackoverflow.com/questions/40121332/why-does-the-where-id-in-n1-n2-n3-n2000-incredibly-slow