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

来源:互联网 发布:vb for循环嵌套if 编辑:程序博客网 时间:2024/04/28 21:11

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

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

select count(1) bcrzc,0 bsjgj,opt_time from t_manual_entry_workload a where opt_type = 'CIQ入暂存' and is_delete = 0union allselect 0 bcrzc,count(1) bsjgj,op_date opt_time from til_inspection_rec where brand = '保时捷' and step = '港检' and  is_deleted = 1

结果如下:


简单的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 = 0union allselect 0 bcrzc,count(1) bsjgj,op_date opt_time from til_inspection_rec where brand = '保时捷' and step = '港检' and  is_deleted = 1) awhere a.opt_time >= '2017-01-01' and a.opt_time <= '2017-11-30'



第二种查询方法:

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



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


阅读全文
0 0