当前位置:Gxlcms > mysql > mysql中如何将几个没有关系的结果集放在一起_MySQL

mysql中如何将几个没有关系的结果集放在一起_MySQL

时间:2021-07-01 10:21:17 帮助过:23人阅读

bitsCN.com 昨天在做报表的时候,遇到要把类型A的数据和类型B的数据横向放在一个表中展示,两个之间没什么关系,哪个的数据量多也不确定,废了段时间,才折腾出如下的解决方法: 需要将SELECT es.name primary_school ,COUNT(DISTINCT esi.stu_id) primary_num FROM……、SELECT es.name AS high_school,COUNT(DISTINCT esi.stu_id) AS high_num FROM……、SELECT COUNT(DISTINCT esi.stu_id) total_num FROM……的结果放到一起,由于结果之间没什么关系,先给获取到的结果添加编号,SELECT @rownumb:=@rownumb+1 AS rownum, resources.* FROM (SELECT @rownumb:=0) r,(……)resources,然后根据编号将三个结果集合并起来:SELECT c.rownum,b.high_school,b.high_num,a.primary_school,a.primary_num, c.total_numFROM (……) bLEFT JOIN (……) a ON a.rownum = b.rownumLEFT JOIN(……) c ON c.rownum = b.rownum 这个结果如果刚好b里面的行数最多是没有问题的,但问题是不知道a、b哪个里面的行数最多,解决这个问题,如果可以用full join就可以直接解决了,但full join对于使用的mysql版本不可用,采取的方法是用union all将几个left join后得到的结果合并在一起:SELECT DISTINCT high_school,high_num,primary_school,primary_num, total_num FROM (SELECT c.rownum,b.high_school,b.high_num,a.primary_school,a.primary_num, c.total_num FROM (……) b LEFT JOIN (……) a ON a.rownum = b.rownum LEFT JOIN (……) c ON c.rownum = b.rownumUNION ALL SELECT c.rownum,b.high_school,b.high_num,a.primary_school,a.primary_num, c.total_num FROM (……) a LEFT JOIN (……) b ON a.rownum = b.rownum LEFT JOIN (……) c ON c.rownum = a.rownum ) ee
作者 LemonYang bitsCN.com

人气教程排行