MySQL计数(*)每天接下来的7天

时间:2015-08-20 20:02:20

标签: mysql

我有以下查询,它会计算所选日期的预订次数

 select count(*) 
 from  isBooked inner join booking
 on isbooked.BookingID = booking.bookingID
 where '2015-08-09' between booking.startDate and booking.endDate;

我想在接下来的7天内运行此查询并显示每天的计数,例如

day     count
1        10
2        9
3        18
4        6
5        1
6        9
7        14

1 个答案:

答案 0 :(得分:0)

基本上它可以是7个查询的UNION:

(
    SELECT CURDATE() AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE CURDATE() BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 1 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 1 DAY) BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 2 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 2 DAY) BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 3 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 3 DAY) BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 4 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 4 DAY) BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 5 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 5 DAY) BETWEEN booking.startDate and booking.endDate;
)
UNION ALL
(
    SELECT DATE_ADD(CURDATE(), INTERVAL 6 DAY) AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE DATE_ADD(CURDATE(), INTERVAL 6 DAY) BETWEEN booking.startDate and booking.endDate;
)

但是如果您需要管理大量数据,则应考虑在数据库上定期处理它并将其放入某个缓存文件或其他表中。

如果你想在很多天内这样做,N SELECT的UNION将无法提高效率。在这种情况下,我建议定义一个包含日期的(临时)表,并在日期上使用JOIN进行sigle查询,例如:

CREATE TEMPORARY TABLE dates (day DATE); -- not necessarily temporary

INSERT INTO dates (day) values ('2015-01-01'), ....

SELECT dates.day AS Date, COUNT(*) AS Available
        FROM isBooked INNER JOIN booking
            ON isbooked.BookingID = booking.bookingID
        WHERE dates.day BETWEEN booking.startDate and booking.endDate
        GROUP BY dates.day;