SQL查询,按给定日期范围选择可用的投标

时间:2015-06-15 17:05:13

标签: sql

我的任务是创建一个支持Web的数据库,客户可以在其中预订露营地场地。

我目前正在处理一个SQL查询,以检查某个日期内可用的投标。

我有一个'Pitch'表,其中包含type_idStartDate列,以及一个包含EndDateSELECT Pitch FROM Pitch AS p WHERE Pitch NOT IN ( SELECT Pitch From Booking As b WHERE b.Pitch IS NOT NULL AND b.Pitch = p.pitch AND (StartDate >= 15/06/2015 AND EndDate <= 20/06/2015) ); 列的“预订”表格。 我目前有这个:

TTTAttributedLabel

2 个答案:

答案 0 :(得分:0)

首先,您应该在引用表格时取出“AS”关键字。这通常只用于列。然后,不要尝试加入您的子查询。它可能看起来像这样:

SELECT PITCH 
FROM PITCH 
WHERE PITCH NOT IN (
    SELECT PITCH FROM BOOKING
    WHERE WHERE STARTDATE >= 15/06/2015 --verify syntax of date
      AND ENDDATE <= 20/06/2015 );

虽然我不建议将列命名为与表相同。

答案 1 :(得分:0)

你也可以像这样使用JOIN (仅返回两个日期期间可用的投球):

SELECT DISTINCT
    p.pitch
FROM
    Pitch p
    JOIN
    Booking b ON p.pitch = b.pitch
WHERE
    b.StartDate >= '2015-06-15' 
AND b.EndDate <= '2015-06-20'

或像这样使用EXISTS

SELECT DISTINCT
    p.pitch
FROM
    Pitch p
WHERE
    EXISTS(    -- or add a `NOT` at first to return only the pitches that are not available during the two dates.
        SELECT 1
        FROM Booking b
        WHERE
            p.pitch = b.pitch
        AND b.StartDate >= '2015-06-15'
        AND b.EndDate <= '2015-06-20'