加油,新时代打工人!
思路:
先查出有数据的县区,用县区编码判断,不存在县区里的数据。然后,用union all进行两个SQL拼接起来。
SELECTt.regionCode,t.regionName,t.testNum,t.sampleNum,t.squareNum,t.cropsCatgoryNum
FROM((SELECTar.`code` AS regionCode,ar.full_name AS regionName,count( tm.id ) AS testNum,IFNULL( sum( tm.sample_num ), 0 ) AS sampleNum,FORMAT( IFNULL( sum( tm.fields_square )/ 1000, 0 ), 3 ) AS squareNum,tc.crops_id AS cropsCatgoryNum FROMt_adminregion arLEFT JOIN t_test_main tm ON SUBSTRING( tm.village, 1, 6 ) = SUBSTRING( ar.`code`, 1, 6 )LEFT JOIN t_test_crops tc ON tc.test_id = tm.id WHEREar.`level` = 22 AND MONTH ( tm.create_time ) = 1 GROUP BYar.`code` ORDER BYar.`code` ) UNION ALLSELECTt1.CODE,t1.full_name,0 AS TestNum,0 AS SampleNum,0 AS SquareNum,0 AS CropsCatgoryNum FROMt_adminregion t1LEFT JOIN (SELECTar.`code` AS regionCode,ar.full_name AS regionName,count( tm.id ) AS testNum,IFNULL( sum( tm.sample_num ), 0 ) AS sampleNum,FORMAT( IFNULL( sum( tm.fields_square )/ 1000, 0 ), 3 ) AS squareNum,tc.crops_id AS cropsCatgoryNum,tm.create_time AS createTime FROMt_adminregion arLEFT JOIN t_test_main tm ON SUBSTRING( tm.village, 1, 6 ) = SUBSTRING( ar.`code`, 1, 6 )LEFT JOIN t_test_crops tc ON tc.test_id = tm.id WHEREar.`level` = 22 AND MONTH ( tm.create_time ) = 1 GROUP BYar.`code` ORDER BYar.`code` ) a ON t1.CODE = a.regionCode WHEREa.regionCode IS NULL AND t1.`level` = 22 ) t
GROUP BYt.`regionCode`
ORDER BYt.`regionCode`