我遇到的情况是,数据库表中有成百上千的行,比如说8列,其中前两列被索引(每列两个索引,两列一个复合索引),并且我有两个SQL查询与分组和联合一样:
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
似乎第二种工会方法的工作速度比第一种方法快两倍(有时更多).
我正在Python中执行此查询,因此第一个是一个内衬,第二个是我需要生成的.
我想知道第二种方法是否正常,可能还有我不知道的第三种方法吗?
更新:
所有查询中的columnTwo和columnOne字段都不唯一
例
# columnOne columnTwo
1 a a
2 b b
3 c b
4 d a
...
用group by来解释查询显示如下:
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 temporary
MyTable中的索引:
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, ,
解决方法: 您看到的是由于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://www./content-2-555351.html
|