MySQL 查詢顯示每月記錄,即使資料遺失
問題:
問題:
在當當您需要從使用者資料表中擷取按月記錄的情況時,您可能會遇到某些月份的資料遺失的情況。如何克服這個問題並確保顯示所有月份,無論它們是否包含資料?
答案:
SELECT COUNT(u.userID) AS total, m.month, YEAR(m.merge_date) AS year FROM ( SELECT '2013-01-01' AS merge_date UNION SELECT '2013-02-01' AS merge_date UNION SELECT '2013-03-01' AS merge_date UNION SELECT '2013-04-01' AS merge_date UNION SELECT '2013-05-01' AS merge_date UNION SELECT '2013-06-01' AS merge_date UNION SELECT '2013-07-01' AS merge_date UNION SELECT '2013-08-01' AS merge_date UNION SELECT '2013-09-01' AS merge_date UNION SELECT '2013-10-01' AS merge_date UNION SELECT '2013-11-01' AS merge_date UNION SELECT '2013-12-01' AS merge_date ) AS m LEFT JOIN users u ON MONTH(m.merge_date) = MONTH(u.userRegistredDate) AND YEAR(m.merge_date) = YEAR(u.userRegistredDate) GROUP BY m.merge_date ORDER BY 1+1;
擷取按月份的使用者記錄,包括對於沒有條目的月份,可以使用派生表和左連接的組合來實現解決方案。
order by 子句用於將結果按月升序排序。
透過使用左連接,查詢從「users」表和衍生表中檢索數據,確保結果包括所有月份,甚至是那些沒有任何相應用戶記錄的月份。以上是如何在 MySQL 中顯示缺失資料的每月記錄?的詳細內容。更多資訊請關注PHP中文網其他相關文章!