昨天在做報表的時候,遇到要把類型A的數據和類型B的數據橫向放在一個表中展示,兩個之間沒什麼關系,哪個的數據量多也不確定,廢了段時間,才折騰出如下的解決方法:
www.2cto.com
需要將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 www.2cto.com
(……) 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
作者 LemonYang