mysql union group by_mysql-UNION vs GROUP BY或更好的解决方案

我遇到的情况是,数据库表中有成百上千的行,比如说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 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.icode9.com/content-2-555351.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值