問題:需要傳入一個時間范圍(比如2017-07-20,2017-07-31),查詢表A,B,C每一天的記錄數,這里聯合查詢應當用full join的,即A full join B on A.date=B.date full join C on A.date=C.date where A.date between '2017-07-20' and '2017-07-31',這樣當A在這一天沒有記錄,但是B或C有,這一天也會有記錄。
但是所用數據庫是mysql,不支持full join。還有一個問題就是即使用full join,如果這幾個表都沒有符合條件的記錄,這一天也沒有記錄,當然這個代碼層面可以處理。
解決思路:
不支持full join就逐表查然后用union all合并
SELECT count(1) as A_count from A
UNION ALL
SELECT count(1) as B_count from B
UNION ALL
SELECT count(1) as C_count from C
但是這樣的結果是
image.png
很明顯,這些數據的別名應該是分開的,修改為
SELECT count(1) as A_count,0 as B_count,0 as C_count from A
UNION ALL
SELECT 0 as A_count,count(1) as B_count,0 as C_count from B
UNION ALL
SELECT 0 as A_count,0 as B_count,count(1) as C_count from C
image.png
還不符合要求,我們需要的是一行數據,而不是三行,這里使用一個小技巧,用sum來合并這三行數據
SELECT sum(A_count) A_count ,sum(B_count) B_count,sum(C_count) C_count from (
SELECT count(1) as A_count,0 as B_count,0 as C_count from A
UNION ALL
SELECT 0 as A_count,count(1) as B_count,0 as C_count from B
UNION ALL
SELECT 0 as A_count,0 as B_count,count(1) as C_count from C
) t
image.png
成功了一半,我們需要每天這幾張表的新增記錄數,即使這一天一個新增記錄也沒有
由于數據庫并沒有日期表,所以需要自己得到日期集合
考慮在java層得到這個時間段的每一天{'2017-07-20","2017-07-21","2017-07-22"......''2017-07-31"},然后傳入mybatis,遍歷生成sql語句。
List<String> dates = new ArrayList<>();
dates.add(startDate);
try {
Date dateOne = dateFormat.parse(startDate);
Date dateTwo = dateFormat.parse(endDate);
Calendar calendar = Calendar.getInstance();
calendar.setTime(dateOne);
while (calendar.getTime().before(dateTwo)) {
dates.add((dateFormat.format(calendar.getTime())));
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
} catch (Exception e) {
logger.warn("時間參數不正確", e);
return null;
}
dates.add(endDate);
List<Map<String, Object>> list = mapper.selectWarning(dates);
mapper.java
List<Map<String, Object>> selectWarning(@Param(value="dates")List<String> dates);
mapper.xml
<select id="selectWarning" resultType="java.util.HashMap">
<foreach collection="dates" item="date" index="index" open="" separator=" union " close="">
SELECT #{date} as date,sum(A_count) A_count ,sum(B_count) B_count,sum(C_count) C_count from (
SELECT count(1) as A_count,0 as B_count,0 as C_count from A where date(create_date)=#{date}
UNION ALL
SELECT 0 as A_count,count(1) as B_count,0 as C_count from B where date(create_date)=#{date}
UNION ALL
SELECT 0 as A_count,0 as B_count,count(1) as C_count from C where date(create_date)=#{date}
) t
</foreach>
order by date desc
</select>
image.png