我遇到的情況是,數據庫表中有成百上千的行,比如說8列,其中前兩列被索引(每列兩個索引,兩列一個復合索引),并且我有兩個SQL查詢與分組和聯(lián)合一樣:
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中執(zhí)行此查詢,因此第一個是一個內襯,第二個是我需要生成的.
我想知道第二種方法是否正常,可能還有我不知道的第三種方法嗎?
更新:
所有查詢中的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優(yōu)化器的限制(在最新版本中可能會大大改進). 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
|