mysql中查询没有数据的行,MySQL从无关联的两个或多个表中查询数据,列转行等...

背景需求:用一条sql查询没有任何关联的两张表,并且查询中涉及到了聚合函数,查询结果需要作为一条数据(列转行)。

两张没有关联的表放到一个结果集中,此处考虑使用union all,

select count(1) bcrzc,0 bsjgj,opt_time from t_manual_entry_workload a where opt_type = 'CIQ入暂存' and is_delete = 0

union all

select 0 bcrzc,count(1) bsjgj,op_date opt_time from til_inspection_rec where brand = '保时捷' and step = '港检' and is_deleted = 1

结果如下:

2096a28e26ce3c65956c2ab403f90eee.png

简单的union all查出来是以不同数据行的形式显示,需要列转行,外边就加了一层查询

select sum(a.bcrzc) bcrzc, sum(a.bsjgj) bsjgj from(

select count(1) bcrzc,0 bsjgj,opt_time from t_manual_entry_workload a where opt_type = 'CIQ入暂存' and is_delete = 0

union all

select 0 bcrzc,count(1) bsjgj,op_date opt_time from til_inspection_rec where brand = '保时捷' and step = '港检' and is_deleted = 1) a

where a.opt_time >= '2017-01-01' and a.opt_time <= '2017-11-30'

c21f2ac5ad3741f2a68a39711ff3771f.png

第二种查询方法:

select (select count(1) from t_manual_entry_workload a where opt_type = 'CIQ入暂存' and opt_time >= '2017-01-01' and opt_time <= '2017-11-30') AAA

,(select count(1) from til_inspection_rec where brand = '保时捷' and step = '港检' and op_date >= '2017-01-01' and op_date <= '2017-11-30') BBB

ff4805c6d942e8f8e52aab36541dc8b0.png

虽然第二种查询看起来稍微简单容易理解一些,但是很明显效率没有第一种高,猜想是由于where后的时间条件重复校验导致的。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值