我们有2张桌子:
CREATE TABLE `task_information`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`project_id` varchar(64) NOT NULL DEFAULT '0',
`task_id` varchar(64) NOT NULL DEFAULT '0',
`machine_id` varchar(16) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
KEY `idx_project` (`project_id`,`task_id`),
KEY `idx_task` (`task_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1100523 DEFAULT CHARSET=utf8mb4
CREATE TABLE `task_process`
(
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`task_id` varchar(64) NOT NULL DEFAULT '0',
`project_id` varchar(64) NOT NULL DEFAULT '0',
`status` varchar(16) NOT NULL DEFAULT '0'
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_task` (`task_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1096437 DEFAULT CHARSET=utf8mb4
这两个表基于“ task_id”具有一对一的关系。
两个表有将近80万个条目。在“状态”列中也将有很多“成功”。 “状态”列正好具有三个值:“成功”,“失败”和“开始”,它们的比率大约为100:1:1。
现在我要选择指定了machined_id且状态等于“成功”的task_id,我的sql查询如下所示:
select *
from task_information
inner join task_process on task_process.task_id = task_information.task_id
and task_information.machine_id = "RA00906"
where task_process.status="success"\G;
这需要4.96s,从解释的结果如下:
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: task_process
partitions: NULL
type: ALL
possible_keys: uniq_task
key: NULL
key_len: NULL
ref: NULL
rows: 760145
filtered: 10.00
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: task_information
partitions: NULL
type: ref
possible_keys: idx_task
key: idx_task
key_len: 258
ref: task_process.task_id
rows: 1
filtered: 10.00
Extra: Using where
但是,如果我将“ =”更改为“ like”,则速度会更快(约0.9秒):
select status
from task_information
inner join task_process on task_process.task_id = task_information.task_id
and task_information.machine_id = "RA00906"
where task_process.status like "success"
explain的结果是这样的:
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: task_information
partitions: NULL
type: ALL
possible_keys: idx_task
key: NULL
key_len: NULL
ref: NULL
rows: 759749
filtered: 10.00
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: task_process
partitions: NULL
type: eq_ref
possible_keys: uniq_task
key: uniq_task
key_len: 258
ref: task_information.task_id
rows: 1
filtered: 11.11
Extra: Using where
这两个查询都返回约500行,但是“ LIKE”比“ =”要快得多,即使它们在功能上应该大致相同。
有人可以向我解释其背后的原因吗?
tl;博士 在相同的“内部联接”查询中,使用“ LIKE”比“ =”要快得多,这是什么原因?