开发者

Why this query is so slow?

This query appears in mysql slow query log: it takes 11 seconds.

INSERT INTO record_visits
( record_id, visit_day )
VALUES
( '567', NOW() );

The table has 501043 records and it's structure looks like this:

CREATE TABLE IF NOT EXISTS `record_visits` (
 开发者_JAVA百科 `id` int(11) NOT NULL AUTO_INCREMENT,
  `record_id` int(11) DEFAULT NULL,
  `visit_day` date DEFAULT NULL,
  `visit_cnt` bigint(20) DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `record_id_visit_day` (`record_id`,`visit_day`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ;

What could be wrong? Why this INSERT takes so long?

UPDATE

I found out, what was the cause of all the troubles. There were a very heavy "ON INSERT" trigger created on that table. Together with MyISAM table locking, it gave enormous query times for the INSERT query. Probably this is why @Oswald in the comments could not reproduce this situation.

Real problem here is that MySQL does not log queries inside of triggers and you always have to remember about them when profiling your application.

Thank you for your help, everyone, accepting answer that was closes to the solution.


I suspect it's not the query itself that is slow, but you're running other queries on the server that is locking the table. MyISAM uses table level locking, so a query that needs a given table will lock all other queries that need that table even if they touch different rows. For example, if you often have long-running SELECT queries, your INSERT, UPDATE and DELETE queries won't be able to execute until all selects that were running when you issued the query complete.

If you say SHOW PROCESSLIST from another prompt while your insert is running you'll probably see that it's in the "Locked" state. If it turns out to be another state, and there are no long-running selects blocking it, you should post that because that will help narrow down the problem too.


I think, when you try adding a data to this table, mysql checks all record_id_visit_day rows because of UNIQUE index.


I don't know MySQL, but does a UNIQUE KEY implies that there is an index on the visit_day column? If not, try creating one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜