简体   繁体   English

选择mysql查询的Perf非常糟糕

[英]Perf of select mysql query is really bad

I'm not sure why this query is taking 4 minutes to complete: 我不确定为什么这个查询需要4分钟才能完成:

SELECT 
    su.sid,u.uid,u.display_name,u.locale 
FROM user u 
LEFT JOIN subscription_user su ON su.uid = u.uid 
ORDER BY u.display_name DESC 
LIMIT 0,25;

Well, I know it's due to the order, remove it and it's very fast. 嗯,我知道这是由于订单,删除它,它非常快。 If I change to using INNER JOIN instead it's fast but the issue is not all users may be in the subscription_user table. 如果我改为使用INNER JOIN而不是快速但问题不是所有用户都可能在subscription_user表中。

CREATE TABLE `user` (
  `uid` int(11) NOT NULL AUTO_INCREMENT,
  `password` varchar(100) DEFAULT NULL,
  `user_type` varchar(10) NOT NULL DEFAULT 'user',
  `display_name` varchar(50) NOT NULL,
  `email` varchar(100) NOT NULL,
  `locale` varchar(8) DEFAULT 'en',
  `last_login` datetime DEFAULT NULL,
  `auth_type` varchar(10) DEFAULT NULL,
  `auth_data` varchar(500) DEFAULT NULL,
  `inactive` tinyint(4) NOT NULL DEFAULT '0',
  `receive_email` tinyint(4) NOT NULL DEFAULT '1',
  `stateid` int(10) DEFAULT NULL,
  `owner_group_id` int(11) DEFAULT NULL,
  `signature` varchar(500) DEFAULT NULL,
  `raw_signature` varchar(500) DEFAULT NULL,
  `round_robin` smallint(5) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`uid`),
  UNIQUE KEY `email` (`email`),
  KEY `stateid` (`stateid`) USING BTREE,
  KEY `user_type` (`user_type`) USING BTREE,
  KEY `name` (`display_name`)
) ENGINE=InnoDB AUTO_INCREMENT=28343 DEFAULT CHARSET=latin1;

CREATE TABLE `subscription_user` (
  `sid` varchar(50) NOT NULL,
  `uid` int(11) NOT NULL,
  `deleted` tinyint(4) NOT NULL DEFAULT '0',
  `forum_user` varchar(50) NOT NULL,
  PRIMARY KEY (`sid`,`uid`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

When you have an SQL query, the index can only really help you if the first column in the index is part of the query. 当您有SQL查询时,如果索引中的第一列是查询的一部分,索引只能真正帮助您。

Your query joins su.uid = u.uid and the optimizer will not be able to use that to reference the first column in the subscription primary key index. 您的查询加入su.uid = u.uid ,优化器将无法使用它来引用订阅主键索引中的第一列。

You should either reverse the order of the columns in the primary key, or alternatively, you should add a foreign key index, or an independent index on the uid 您应该反转主键中列的顺序,或者您应该在uid上添加外键索引或独立索引

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM