我遇到的情况是,数据库表中有数十万行,假设有8列,其中前两列被索引(每个列有两个索引,两个列都有一个复合索引),还有两个SQL查询,其中group和union类似:
SELECT MIN(columnOne), columnTwo FROM MyTable
WHERE columnTwo IN (1,2,3)
GROUP BY columnTwo和
SELECT MIN(columnOne), columnTwo FROM MyTable WHERE columnTwo = 1
UNION
SELECT MIN(columnOne), columnTwo FROM MyTable WHERE columnTwo = 2
UNION
SELECT MIN(columnOne), columnTwo FROM MyTable WHERE columnTwo = 3而且,第二种使用unions的方法似乎比第一种快两倍(有时甚至更多)。
我在Python中执行这个查询,所以第一个查询是一个队列,第二个查询是我需要生成的。
我不知道第二种方法是否正常,也许还有第三种我不知道的方式?
更新:
所有查询中的columnTwo和columnOne字段都是,而不是唯一的。
示例
# columnOne columnTwo
1 a a
2 b b
3 c b
4 d a
...使用组解释查询,如下所示:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE MyTable index secondColIndex,bothColIndex bothColIndex 12 1623713 Using where对联合查询的解释显示如下:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY MyTable ref secondColIndex,bothColIndex bothColIndex 4 const 217472 Using where
2 UNION MyTable ref secondColIndex,bothColIndex bothColIndex 4 const 185832 Using where
3 UNION MyTable ref secondColIndex,bothColIndex bothColIndex 4 const 175572 Using where
UNION RESULT <union1,2,3> ALL Using temporaryMyTable中的索引:
Table, Non_unique, Key_name, Seq_in_index, Column_name, Collation, Cardinality, Sub_part, Packed, Null, Index_type, Comment, Index_comment
MyTable, 0, PRIMARY, 1, Id, A, 1623713, , , , BTREE, ,
MyTable, 1, columnOneIndex, 1, columnOne, A, 1623713, , , , BTREE, ,
MyTable, 1, columnTwoIndex, 1, columnTwo, A, 5737, , , , BTREE, ,
MyTable, 1, bothColumnsIndex, 1, columnTwo, A, 5171, , , , BTREE, ,
MyTable, 1, bothColumnsIndex, 2, columnOne, A, 1623713, , , , BTREE, , 发布于 2017-11-24 13:39:58
您所看到的原因是MySQL优化器的局限性(在最近的版本中可能有很大改进)。GROUP BY几乎总是导致文件排序,限制了索引的使用。
一种选择基本上只是简化UNION版本,但使用相关的子查询:
SELECT x.columnTwo,
(SELECT MIN(columnOne)
FROM myTable t
WHERE t.columnTwo = x.columnTwo
) as min_columnOne
FROM (SELECT 1 as columnTwo UNION ALL
SELECT 2 as columnTwo UNION ALL
SELECT 3 as columnTwo
) x;这在本质上应该具有与UNION版本相同的性能。关联子查询应该使用索引进行计算。
https://stackoverflow.com/questions/47471521
复制相似问题