2014-09-30 31 views
0

我有一个频繁更新和选择的队列表(8个并发线程)。每个线程的操作是:MySQL查询,选择或更新时性能降低

- count for queue_process_id 
- count == 0, update 10 new items with queue_process_id = N 
- select and search for queue_process_id 

队列表:

CREATE TABLE `queue` (
    `queue_id` int(11) NOT NULL AUTO_INCREMENT, 
    `queue_module_id` tinyint(4) NOT NULL, 
    `queue_action` int(11) NOT NULL, 
    `queue_value` text NOT NULL, 
    `queue_value2` varchar(32) NOT NULL, 
    `queue_priority` smallint(6) NOT NULL, 
    `queue_order` smallint(6) NOT NULL, 
    `queue_process_id` tinyint(4) NOT NULL DEFAULT '99', 
    PRIMARY KEY (`queue_id`), 
    KEY `queue_priority` (`queue_priority`), 
    KEY `queue_module_id` (`queue_module_id`), 
    KEY `queue_action` (`queue_action`), 
    KEY `queue_order` (`queue_order`), 
    KEY `queue_process_id` (`queue_process_id`) 
) ENGINE=InnoDB AUTO_INCREMENT=2502029 DEFAULT CHARSET=utf8 | 

这是用于更新新项目的查询:

update queue set queue_process_id = N where queue_module_id = N and queue_process_id = 99 order by queue_priority desc limit 10 

queue_module_id为不同的模块。每个模块都有N个线程,所有这些线程都使用同一个表。

这个结果对EXPLAIN语句(更新切换选择):

mysql> explain select SQL_NO_CACHE * from queue where queue_module_id = 1 and queue_process_id = 99 order by queue_priority desc limit 10; 

    +----+-------------+-------+-------+----------------------------------+----------------+---------+------+------+-------------+ 
    | id | select_type | table | type | possible_keys     | key   | key_len | ref | rows | Extra  | 
    +----+-------------+-------+-------+----------------------------------+----------------+---------+------+------+-------------+ 
    | 1 | SIMPLE  | queue | index | queue_module_id,queue_process_id | queue_priority | 2  | NULL | 20 | Using where | 
    +----+-------------+-------+-------+----------------------------------+----------------+---------+------+------+-------------+ 

update语句需要最多13秒完成(!)。我不知道如何优化查询或索引。也许有人可以帮助我在这里。

谢谢。

回答

1

这是你update查询:

update queue 
    set queue_process_id = N 
    where queue_module_id = N and queue_process_id = 99 
    order by queue_priority desc 
    limit 10; 

(我假设N是一个占位符,因为它缺乏需要恒定的报价。)

您可以通过索引速度这一点。最好的索引是queue(queue_module_id, queue_process_id, queue_priority)。你可以创建这个使用:

create index idx_queue_3 on queue(queue_module_id, queue_process_id, queue_priority) 
+0

很好的答案。 CPU从100%到0-2%。我真的必须考虑索引。谢谢。 – hberg539 2014-09-30 13:08:50