Mysql工作上遇到的小技巧
MySQL技巧
一、聚合函数
需要使用聚合函数算sum()或者使用max()但是,由于聚合函数需要将查询到的所有其他不是聚合函数的字段都要group by那么问题来了,有时候业务如果全都group by了会得不到想要的值。。
最近发现解决办法
可以使用嵌套查询
select
t1.repair_status as repairStatusName,
t2.code as deviceNumber,
t2.deviceType as deviceTypeCode
from dg_device_check t1,
(select u1.device_code as code,
u1.device_type as deviceType,
max(u1.create_time) as createTime
from dg_device_check u1
left join md_device u2 on u1.device_code = u2.code
where u2.section = #{miningAreaCode}
group by code,deviceType) t2
where t1.create_time = t2.createTime;
将先要聚合查询的查出来,然后作为表继续查询。
注意 如果两个表的查询条件互斥或者查询条数不同则不可这样使用
二、巧妙使用mysql的函数
如sum与if结合
下面是使用场景:
一个数据表有一个字段:验证状态:0->未验证 1->正在验证 2->已验证
这时候有个业务需要统计这个字段的三种状态的信息。
select sum(IF(t1.status = '0', 1, 0)) as waitRectifyCount,
sum(IF(t1.status = '1', 1, 0)) as inRectifyCount,
sum(IF(t1.status = '2', 1, 0)) as doneRectifyCount
from t1;
if判断条件,符合为1不符合为0
查出所有值后再求和 就能得到数值
三、order by使用
一般都使用一个字段去排序,如果遇到如果一个字段A相同了,想要按照B字段去排序的时候,怎么办呢?
order by A desc,B desc 这样就可以了
【小坑】 不要在order by中使用没有定义在select中的别名组合(运算)
例如:
select sum(count1) as total1,
sum(count2) as total2
from test
group by type
order by total1 + total2 desc;
可能你以为,这样可以,但是!不行!
原理暂时不理解。。可能是生成的临时表中没有 total1 + total2字段吧。。

浙公网安备 33010602011771号