こんにちは、12 か月前の時間枠で月ごとに発生したドライブを取得する次のクエリがあります。ただし、結果は正しくありません。たとえば、テスト データベースでは 2 月に発生したドライブは 3 つしかありませんが、結果セットでは 9 つのドライブが表示されます。
SELECT mlist.m, count(data.month) as drvs
FROM users, (
SELECT 'Jan' AS m
UNION SELECT 'Feb' AS m
UNION SELECT 'Mar' AS m
UNION SELECT 'Apr' AS m
UNION SELECT 'May' AS m
UNION SELECT 'Jun' AS m
UNION SELECT 'Jul' AS m
UNION SELECT 'Aug' AS m
UNION SELECT 'Sep' AS m
UNION SELECT 'Oct' AS m
UNION SELECT 'Nov' AS m
UNION SELECT 'Dec' AS m
) AS mlist LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, '%b') AS month,
drives.timestamp,
CONCAT(drivers.name, ' ', drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.user = '146'
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON mlist.m = data.month GROUP BY mlist.m
結果:
"4月","3" "8月","3" "12月","6" "2月","9" "1月","3" "7月","3" "6月","3" " 3月","3" "5月","3" "11月","3" "10月","6" "9月","3"