您好我正在使用此sql查询获取基于月份的最近12个月的图表来表示图表:
SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,
DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,
drives.departure,
drives.destination,
drives.route,
CONCAT(drivers.name, " ", drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.driver = drivers.id
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH) ORDER BY drives.timestamp Asc
然而,如果一个月没有记录,它不会按预期包含在结果集中,我正在用php做很多计算来完成我想要的。
我的问题是:有没有办法检索一个简单的结果集,其中包含过去12个月每个月的驱动器总数,如果一个月有0个驱动器,则必须包含它 - 显示在结果中集。
答案 0 :(得分:3)
您需要使用包含每个月行的表进行外部联接。假设您没有这样的表,可以使用硬编码的UNION查询动态创建它:
SELECT * FROM
(SELECT DATE_FORMAT(now(), "%b") as Month
UNION
SELECT DATE_FORMAT(now() - INTERVAL 1 MONTH), "%b")
UNION
SELECT DATE_FORMAT(now() - INTERVAL 2 MONTH), "%b")
UNION
...
SELECT DATE_FORMAT(now() - INTERVAL 11 MONTH), "%b")) AS Months
LEFT JOIN (SELECT DATE_FORMAT(drives.timestamp, "%b") AS Month,
drives.timestamp,
DATE_FORMAT(drives.timestamp, "%d-%m-%Y %H:%i:%s") AS Exact_date,
drives.departure,
drives.destination,
drives.route,
CONCAT(drivers.name, " ", drivers.surname) as driver,
drivers.id as driver_id
FROM drives, drivers WHERE drives.driver = drivers.id
AND drives.timestamp > DATE_SUB(now(), INTERVAL 12 MONTH)) data
ON Months.Month = data.Month
ORDER BY data.timestamp
任何没有记录的月份都会在数据列中有一行NULL
。