1

我有一个预订系统,我想显示列表的月历视图。我有以下表结构(还有很多其他列);

CREATE TABLE `sys_calendar` (
    `dt` date NOT NULL,
    PRIMARY KEY (`dt`)
);

CREATE TABLE `listings` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `title` varchar(255) NOT NULL,
    PRIMARY KEY (`id`),
);

CREATE TABLE `bookings` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `listing_id` int(10) unsigned NOT NULL,
    `start_date` date NOT NULL,
    `end_date` date NOT NULL,
    PRIMARY KEY (`id`)
);

sys_calendar保存从2000-01-012040-12-31的所有日期;

dt
------------
2000-01-01
2000-01-02
2000-01-03
....
2040-12-30
2040-12-31

我想要做的是显示特定列表的月历。例如; 我想listing_id在 2013 年 4 月(在 2013-04-01 和 2013-04-30 之间bookings)显示一个日历 = 10。

dt         | Availability
-------------------------
2013-04-01 | No
2013-04-02 | No
2013-04-03 | Yes
2013-04-04 | Yes
2013-04-05 | Yes
2013-04-06 | Yes
....
2013-04-29 | No
2013-04-30 | Yes

我知道我必须加入sys_calendarbookings表格,但不知道如何。

4

1 回答 1

1

我认为这对你有用:

SELECT  c.dt,
        CASE WHEN COUNT(b.id) > 0 THEN 'No' ELSE 'Yes' END AS Availability
FROM    sys_calendar c
        LEFT JOIN bookings b
            ON b.Listing_id = 10
            AND c.dt BETWEEN b.Start_Date AND b.End_Date
GROUP BY c.dt;

SQL Fiddle 示例

此外,如果您想显示多个可用性,您可以使用:

SELECT  c.dt,
        CASE WHEN COUNT(CASE WHEN b.Listing_id = 1 THEN 1 END) > 0 THEN 'No' ELSE 'Yes' END AS Availability1,
        CASE WHEN COUNT(CASE WHEN b.Listing_id = 2 THEN 1 END) > 0 THEN 'No' ELSE 'Yes' END AS Availability2,
        CASE WHEN COUNT(CASE WHEN b.Listing_id = 3 THEN 1 END) > 0 THEN 'No' ELSE 'Yes' END AS Availability3,
        CASE WHEN COUNT(CASE WHEN b.Listing_id = 4 THEN 1 END) > 0 THEN 'No' ELSE 'Yes' END AS Availability4
FROM    sys_calendar c
        LEFT JOIN bookings b
            ON c.dt BETWEEN b.Start_Date AND b.End_Date
WHERE   c.dt BETWEEN '20130401' AND '20130430'
GROUP BY c.dt;

SQL Fiddle 示例

于 2013-04-24T18:23:15.280 回答