一旦在SQL查询中有价值,如何阻止某些东西再次出现?

时间:2019-04-27 21:50:35

标签: sql sql-server

我知道之前可能已经有人问过,但是我需要帮助。 我有一个customerID为PK的表客户,一个carID为PK的表车,并且reservationID为PK和carID,customerID为FK的表预订。 在datagridview中,我执行了一个查询以查看汽车并租车,当客户租车时,怎么可能不向他展示其他车呢? 换句话说,我希望有租金的客户不要看到可用的汽车。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了您的问题,就会这样:

-- Current customer, should come from outside (provided by the application, etc.)
declare @CustomerId int = ...;

select c.*
from dbo.Cars c
where
  -- Exclude cars booked by other customers
  not exists (
    select 0 from dbo.Reservations r
    where r.CarId = c.Id
      and r.CustomerId != @CustomerId
  )
  -- Exclude everything else if the customer already has a booking
  and not exists (
    select 0 from dbo.Reservations r
    where r.CustomerId = @CustomerId
      and r.CarId != c.CarId
    );