2016-11-20 119 views
0

有些人可以解释为什么用IN子句超过5000条记录的查询太慢吗?有人可以告诉我为什么这是Query非常慢?

表strucuture

CREATE TABLE IF NOT EXISTS `wp_transactions_log` (
    `sync_sequence` bigint(20) unsigned NOT NULL COMMENT 'the sequence number of the sync process/operation that this transaction belong to ', 
    `objectid` varchar(100) NOT NULL COMMENT 'the entity/record id', 
    `wp_id` bigint(20) unsigned NOT NULL, 
    `table_name` varchar(100) NOT NULL COMMENT 'the target wordpress table name this transaction occured/fail for some reason', 
    `logical_table_name` varchar(100) NOT NULL, 
    `operation` varchar(20) NOT NULL COMMENT 'inser/update/delete', 
    `status` varchar(20) NOT NULL COMMENT 'status of the transaction: success,fail', 
    `fail_count` int(10) unsigned NOT NULL COMMENT 'how many this transaction failed', 
    `fail_description` text NOT NULL COMMENT 'a description of the failure', 
    `createdon` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, 
    PRIMARY KEY (`sync_sequence`,`objectid`,`table_name`,`operation`,`wp_id`), 
    KEY `objectid` (`objectid`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; 

此表包含5K记录。

查询:

SELECT wp_id,objectId FROM wp_transactions_log WHERE `operation` = "insert" AND `wp_id` != 0 AND `status` != "ignore" AND `table_name` ='itg_wpclass_dates' AND objectId IN (... 5k record) 

即使这个查询是相同的:

SELECT wp_id,objectId FROM wp_transactions_log WHERE objectId IN (5k record) 

注:在IN子句所有的参数都是自己在表中的行相同。 我的意思是慢需要超过15秒。

+0

http://stackoverflow.com/questions/4226035/why-does-a-query-slow-down-drastically-if-in-the-where-clause-a-constant-is-repl –

+0

太慢了,你的意思是多少秒?几年前我做了类似的测试,在'IN'子句中使用了10K,并在'0.04'秒内执行。 http://stackoverflow.com/a/7818697/153723我相信问题不在桌子上。 – Ergec

+0

不,它超过15秒 –

回答

0

查询速度很快,需要200ms才能执行,但处理查询和检索数据的时间很长。我认为没有办法减少这个时间。

2

objectid未编入索引。复合主键仅被索引。在objectid上添加索引,然后尝试。

ALTER TABLE wp_transactions_log ADD INDEX (objectid); 

但如果你有大量的数据,然后添加索引会锁定您的元数据,使用INPLACE算法以最小的锁争做到这一点。

此外,在你选择语句之前,只需添加Explain并向我们提供响应。这将是一个很好的指标,可以在您的表中找出问题。

+0

我在objectid上创建了索引,但是没用。 –

+0

可以显示解释结果选择wp_id,objectId FROM wp_transactions_log WHERE objectId IN(5k记录) – Naruto

+0

结果如下: id | SELECT_TYPE |表|键入| possible_keys |关键| key_len |裁判|行|额外 1 | SIMPLE | wp_transactions_log |指数| OBJECTID | OBJECTID | 402 | NULL | 5000 |在哪里使用;使用索引 –

相关问题