sql server内连接查询未执行

时间:2013-12-08 12:14:21

标签: sql-server

这个查询有什么问题? 这些是我正在使用的表格 -

create table PS3_Vehicle 
(
    ID int IDENTITY(1,1) NOT NULL Primary Key,
    DealerID varchar(255) NOT NULL,
    VehicleID varchar(255) UNIQUE NOT NULL,
    VehicleName varchar(255) NOT NULL,
    Capacity BIGINT NOT NULL    
);

create table PS3_VehicleBooking
(
  ID int IDENTITY(1,1) NOT NULL Primary Key,
  BookingID varchar(255) NOT NULL UNIQUE,
  VehicleID varchar(255) NOT NULL,
  StartDate date NOT NULL,
  EndDate date NOT NULL
);

CREATE TABLE PS3_Dealer(
    ID int IDENTITY(1,1) NOT NULL Primary KEY,
    DealerID varchar(255) NULL,
    DealerName varchar(255) NOT NULL,
    ContactNo varchar(255) NOT NULL,
    NoOfVehicles bigint NOT NULL,
    CommittedDate date NOT NULL
);

SELECT DealerID, PS3_Vehicle.VehicleID, VehicleName, StartDate, EndDate
FROM PS3_Vehicle
INNER JOIN PS3_VehicleBooking ON PS3_Vehicle.VehicleID != PS3_VehicleBooking.VehicleID AS W
INNER JOIN PS3_Dealer ON W.DealerID = PS3_Dealer.DealerID
  AND CommittedDate > GETDATE();

4 个答案:

答案 0 :(得分:1)

我认为你可以在LEFT JOINPS3_Vehicle之间使用简单的PS3_VehicleBooking进行操作,其中PS3_VehicleBooking与该车辆不匹配:

SELECT v.DealerID, v.VehicleID, v.VehicleName, vb.StartDate, vb.EndDate
FROM PS3_Vehicle v
LEFT JOIN PS3_VehicleBooking vb ON v.VehicleID = vb.VehicleID
WHERE vb.VehicleID IS NULL

这将为您提供PS3_VehicleBooking中不存在的车辆,这使startDateendDate始终NULL

答案 1 :(得分:0)

试试这个:

SELECT w.DealerID, w.VehicleID, w.VehicleName, b.StartDate, b.EndDate
FROM PS3_Vehicle w
INNER JOIN PS3_VehicleBooking b ON w.VehicleID != b.VehicleID 
INNER JOIN PS3_Dealer d ON W.DealerID = d.DealerID
  AND CommittedDate > GETDATE();

http://sqlfiddle.com/#!3/8f5c0/6

答案 2 :(得分:0)

SELECT v.DealerID, v.PS3_Vehicle.VehicleID, v.VehicleName, b.StartDate, b.EndDate
FROM PS3_Vehicle v
Left JOIN PS3_VehicleBooking b ON v.VehicleID = b.VehicleID
INNER JOIN PS3_Dealer d ON v.DealerID = d.DealerID
Where b.VehicleID is null
AND d.CommittedDate > GETDATE()

将为您提供所有未经预订的车辆和有关未经销售的经销商的信息。

当您开始执行此类查询时,请使用别名或表名完全限定所有名称,这为下一位开发人员提供了便利。

哦,startdate和enddate在这个查询中总是为空,所以没有意义。

答案 3 :(得分:0)

SELECT D.DealerID, V.VehicleID, V.VehicleName, vb.StartDate, vb.EndDate
FROM PS3_Dealer D LEFT JOIN  PS3_Vehicle V 
ON D.DealerID = V.DealerID 
LEFT JOIN PS3_VehicleBooking vb
ON V.VehicleID = VB.V.VehicleID
WHERE vb.V.VehicleID IS NULL
AND CommittedDate > GETDATE();