SQL选择表中不在日期之间的行

时间:2014-02-04 16:33:03

标签: sql sql-server date between

我有以下代码:

SELECT 
ROOM_DESCRIPTION_DESC AS "DESCRIPTION",
COUNT(ROOM_DESCRIPTION_ID) AS "AMOUNT"
FROM ROOM_TAB
JOIN ROOM_DESCRIPTION_TAB ON ROOM_DESCRIPTION = ROOM_DESCRIPTION_ID
JOIN RESERVATION_TAB ON RESERVATION_ROOM = ROOM_ID
WHERE RESERVATION_FROM NOT BETWEEN '2014-02-10' AND '2014-02-11'
GROUP BY  ROOM_DESCRIPTION_DESC;

我基本上想找到特定日期之间没有预订的房间 问题是,当RESERVATION_TAB中没有记录时,甚至不考虑房间

即:

ROOM_TAB:

| ROOM_ID | ROOM_PRICE | ROOM_DESCRIPTION |
     1          200             1
     2          250             1

ROOM_DESCRIPTION_TAB:

| ROOM_DESCRIPTION_ID | ROOM_DESCRIPTION_DESC |
      1                     single room

RESERVATION_TAB:

| RESERVATION_ID | RESERVATION_FROM | RESERVATION_TO | RESERVATION_ROOM |
        1              2014-02-14       2014-02-16            1

使用我提供的代码提供输出:

| DESCRIPTION | AMOUNT |
  single room     1

这是id为1的房间,第二个房间似乎不存在

2 个答案:

答案 0 :(得分:3)

您需要LEFT JOINRESERVATION_TAB表,因此它将包含来自ROOM_TAB的所有行,而不在RESERVATION_TAB中的行将包含Null } RESERVATION_FROM日期列。

SELECT 
ROOM_DESCRIPTION_DESC AS "DESCRIPTION",
COUNT(ROOM_DESCRIPTION_ID) AS "AMOUNT"
FROM ROOM_TAB
JOIN ROOM_DESCRIPTION_TAB ON ROOM_DESCRIPTION = ROOM_DESCRIPTION_ID
LEFT JOIN RESERVATION_TAB ON RESERVATION_ROOM = ROOM_ID
WHERE RESERVATION_FROM NOT BETWEEN '2014-02-10' AND '2014-02-11'
GROUP BY  ROOM_DESCRIPTION_DESC;

答案 1 :(得分:1)

您需要左连接才能在没有适用的预订记录的情况下查找房间。

SELECT 
ROOM_DESCRIPTION_DESC AS "DESCRIPTION",
COUNT(ROOM_DESCRIPTION_ID) AS "AMOUNT"
FROM ROOM_TAB
JOIN ROOM_DESCRIPTION_TAB ON ROOM_DESCRIPTION = ROOM_DESCRIPTION_ID
LEFT JOIN RESERVATION_TAB ON RESERVATION_ROOM = ROOM_ID
    AND RESERVATION_FROM NOT BETWEEN '2014-02-10' AND '2014-02-11'
WHERE RESERVATION_ID IS NULL
GROUP BY  ROOM_DESCRIPTION_DESC