Why does the “where id in (n1, n2, n3, …, n2000)” incredibly slow? [duplicate]

隐身守侯 提交于 2019-12-12 04:21:39

问题


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

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