MySql使用单独的查询或子查询更快?

时间:2014-04-16 14:25:48

标签: mysql sql

以下查询花了 0.2630秒从表格中的85862行中选择2477行

(SELECT 1, `name` FROM `tab1` WHERE `reg` = 5 and `lang` = 9 and `queue` = 
   (select min(`queue`) from tab1 where `reg` = 5 and `lang` = 9)
limit 5)
UNION ALL
(SELECT 2, `name` FROM `tab1` WHERE `reg` = 1 and `lang` = 3 and `queue` =
   (select min(`queue`) from tab1 where `reg` = 1 and `lang` = 3)
limit 5)
UNION ALL
(SELECT 3, `name` FROM `tab1` WHERE `reg` = 3 and `lang` = 11 and `queue` =
   (select min(`queue`) from tab1 where `reg` = 3 and `lang` = 11)
limit 5)

理论上,如果为了检测列的MIN(value),我会运行单独的查询而不是子查询吗?

reglang已编入索引,queue不是

说明:

| id | select_type | table       | type        | possible_keys | key      | key_len | ref  | rows| Extra
-----+-------------+-------------+-------------+---------------+----------+---------+------+-----+---------------------------------------
| 1  | PRIMARY     | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 813 | Using intersect(lang,reg); Using where
| 2  | SUBQUERY    | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 813 | Using intersect(lang,reg); Using where
| 3  | UNION       | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 830 | Using intersect(lang,reg); Using where
| 4  | SUBQUERY    | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 830 | Using intersect(lang,reg); Using where
| 5  | UNION       | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 834 | Using intersect(lang,reg); Using where
| 6  | SUBQUERY    | tab1        | index_merge | reg,lang      | lang,reg | 1,1     | NULL | 834 | Using intersect(lang,reg); Using where
|NULL| UNION RESULT| <union1,3,5>|  ALL        | NULL          | NULL     | NULL    | NULL | NULL| Using temporary

1 个答案:

答案 0 :(得分:2)

MySQL应该运行&#34; min&#34;每个组只有一次子查询。将值放在单独的变量中不应该真正影响性能。

如果要优化此查询的性能,请在tab1(reg, lang, queue)上创建索引。该索引将允许直接查找值,而无需通过&#34; index merge&#34;步骤