SQL查询 - 我哪里错了?

时间:2009-06-12 12:04:35

标签: sql

我有两张桌子,一张用于开放,另一张用于预订。预订表中的条目总是指开口,每个开口可能有多个预订。我想提取所有预订与bookingType 'C'不同的空缺。

  

E.g。

     
      
  1. 如果开口有3个A,B和C类预订,则不应该出现   在结果

  2.   
  3. 如果一个开口只有A和B类型的预订,它应该显示在   结果

  4.   

以下是我尝试的但是它不正确,因为示例1失败了:

select op.id, bo.id 
  from opening op
  left join booking bo on bo.openingId = op.id
  where bo.bookingType != 'C';

以下是涉及时间间隔的完整查询:

select op.id, bo.id 
  from opening op
  left join booking bo on bo.openingId = op.id
  where ((bo.arrivalDate < '2009/06/20' AND bo.departureDate <= '2009/06/20') OR 
         (bo.arrivalDate >= '2009/06/27' AND bo.departureDate > '2009/06/27')) 

我以前称之为bookingType的实际上是通过两列arrivalDatedepartureDate定义的时间间隔:在上面的示例中,我需要所有未预订的空缺在20th June 200927th June 2009

之间

4 个答案:

答案 0 :(得分:7)

SELECT op.id 
FROM opening op 
WHERE op.id NOT IN 
     (SELECT b.openingid 
      FROM booking b 
      WHERE b.bookingtype='C')

日期更改:

SELECT op.id 
FROM opening op 
WHERE op.id NOT IN 
     (SELECT b.openingid 
      FROM booking b 
      WHERE (b.arrivalDate BETWEEN '2009/06/20' AND '2009/06/27') 
             OR 
            (b.departureDate BETWEEN  '2009/06/20' and '2009/06/27')
     )

答案 1 :(得分:2)

这是一个没有连接的简单版本,你甚至不需要开口表:

select openingId, id
from booking
where openingId not in (
    select openingId
    from booking
    where bookingType = 'C'
)

答案 2 :(得分:1)

@Frankie - 不需要NOT IN子句。您也可以使用Left-Anti-Semi Join - 就像这样:

SELECT op.id 
FROM opening op 
LEFT OUTER JOIN booking b ON op.id = b.openingid AND b.bookingtype = 'C'
WHERE b.OpeningID IS NULL

和此:

SELECT op.id 
FROM opening op 
LEFT OUTER JOIN booking b ON op.id = b.OpeningID
 AND b.ArrivalDate BETWEEN '2009/06/20' AND '2009/06/27'  
 AND b.DepartureDate BETWEEN '2009/06/20' AND '2009/06/27'
WHERE b.OpeningID IS NULL

答案 3 :(得分:0)

select opid, boid from 
   (select op.id opid, bo.id boid, bo.bookingType bookingType 
       from 
       openings op left outer join bookings bo on op.id = bo.id
   )
where bookingType <> 'C'