Home >Database >Mysql Tutorial >MySQL中如何将几个没有关系的结果集放在一起

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

WBOY
WBOYOriginal
2016-06-07 17:14:281030browse

MySQL中如何将几个没有关系的结果集放在一起,刚好b里面的行数最多是没有问题的,但问题是不知道a、b哪个里面的行数最多,解决这个

在做报表的时候,遇到要把类型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_num
FROM
(……) b
LEFT JOIN
(……) a
ON a.rownum = b.rownum
LEFT 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.rownum
UNION 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

linux

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn