2

我有两张桌子:

第一的 :

CREATE TABLE `dialog_projects` (
`id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`creator_user_id` INT(11) UNSIGNED NOT NULL,
`add_users_allowed` INT(1) NULL DEFAULT '1',
`dlg_name` VARCHAR(200) NOT NULL,
`dlg_date` DATETIME NOT NULL,
PRIMARY KEY (`id`),
INDEX `dialog_projects_creator_user_id_ind` (`creator_user_id`),
INDEX `dialog_projects_add_users_allowed_ind` (`add_users_allowed`),
INDEX `dialog_projects_dlg_date_ind` (`dlg_date`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
AUTO_INCREMENT=220094
/*!50100 PARTITION BY KEY (id)
PARTITIONS 10  */;

第二 :

CREATE TABLE `dialog_users` (
`dialog_projects_id` INT(11) UNSIGNED NOT NULL,
`user_id` INT(11) UNSIGNED NOT NULL,
`num_new_msgs` INT(11) UNSIGNED NOT NULL,
`accepted` TINYINT(1) NULL DEFAULT '0',
`last_visit` DATETIME NOT NULL,
PRIMARY KEY (`dialog_projects_id`, `user_id`, `num_new_msgs`),
INDEX `dialog_projects_accepted_ind` (`accepted`),
INDEX `dialog_projects_last_visit_ind` (`last_visit`)
)
COLLATE='utf8_general_ci'
ENGINE=InnoDB
/*!50100 PARTITION BY HASH (dialog_projects_id + user_id + num_new_msgs)
PARTITIONS 10  */;

此查询执行大约 5,5 秒,但没有“order by du.num_new_msgs desc” - 需要 0,005 秒。如何提高速度?怎么了?

#explain 
select SQL_NO_CACHE dp.id
from `dialog_users` as du 
left join `dialog_projects` as dp
 on (du.dialog_projects_id = dp.id) 
where dp.id > 300 and du.num_new_msgs > -1 
    and dp.add_users_allowed = 0 and du.user_id = 10990 

order by du.num_new_msgs desc, dp.id desc 
limit 10

这里解释一下:

"id"    "select_type"   "table" "type"  "possible_keys" "key"   "key_len"   "ref"   "rows"  "Extra"
"1" "SIMPLE"    "dp"    "ref"   "PRIMARY,dialog_projects_add_users_allowed_ind" "dialog_projects_add_users_allowed_ind" "5" "const" "100246"    "Using where; Using index; Using temporary; Using filesort"
"1" "SIMPLE"    "du"    "ref"   "PRIMARY"   "PRIMARY"   "8" "sport-event.dp.id,const"   "1" "Using where; Using index"

谢谢

4

1 回答 1

1

为什么将子句放在ORDER BY子句之前会降低性能LIMIT?因为没有ORDER BYMySQL 查询引擎只需要返回十个方便的行,然后就可以停止了。它ORDER BY需要检查结果集中的每一行以找到您想要的行。

您的查询说明了这一点。为了清楚起见,我对条款进行了重新排序。

 where dp.id > 300 and dp.add_users_allowed = 0 
   and du.num_new_msgs > -1 and du.user_id = 10990 

dialog_projects您可以尝试在列上放置复合索引(add_users_allowed, id)。这可能有助于加快对该表的查找。

您似乎正在为一个相对较小的表(300K 行)使用分区。这可能会影响您的查询性能。大多数 MySQL 用户甚至不会考虑对他们的表进行分区,直到他们的行数至少是你的一百倍。然后他们非常仔细地计划查询,因此大多数查询涉及有限数量的分区;希望只有一个。

于 2018-01-05T20:28:24.033 回答