2

您好我正在使用这个 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 个驱动器,它也必须包含在结果集中显示。

4

1 回答 1

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任何没有记录的月份都会在数据列中有一行。

于 2013-11-03T20:14:09.780 回答