SQL比较两个表中的数据

时间:2012-03-06 12:41:58

标签: sql oracle-sqldeveloper

我有两张桌子路线和预订

CREATE TABLE Route (
RouteID numeric(4),
RouteIMG blob,
RDetails varchar2(40),
CONSTRAINT Route_pk PRIMARY KEY (RouteID));

CREATE TABLE Booking (
BookingID numeric(4),
BookingType varchar2(1),
StartTime date,
EndTime date,
Date date,
History varchar2(25),
RouteID numeric(4),
ExaminerID numeric(4),
InstructorID numeric(4),
StudentID numeric(4),
CONSTRAINT Booking_pk PRIMARY KEY (BookingID),
CONSTRAINT Route_fk FOREIGN KEY (RouteID) REFERENCES Route,
CONSTRAINT Student_fk FOREIGN KEY (StudentID) REFERENCES Student);

我想将Booking.RouteIdRoute.RouteId进行比较,并返回不在预订表中的ID。

例如,

路线表包含路线ID's 0001
技术
0003

并且在预订表中预订的路线为
0001
0002

如何完成此比较并返回值
0003

5 个答案:

答案 0 :(得分:2)

您可以使用left join然后检查booking_id是否为空。

SELECT r.route_id 
FROM Route r LEFT JOIN Booking b ON r.route_id=b.RouteId
WHERE b.RouteId  is null

或者您可以使用:

SELECT r.RouteID 
FROM Route r 
WHERE RouteID NOT IN(SELECT b.RouteId FROM Booking b)

答案 1 :(得分:0)

尝试以下查询:

select R.RouteID 
from Route R 
where RouteID not in (select B.RouteId from Booking B)

答案 2 :(得分:0)

select route_id from route 
where route_id not in ( select route_id from booking )

答案 3 :(得分:0)

SELECT
    Route.RouteID
FROM
    Route
WHERE
    NOT EXISTS
    (SELECT
        NULL
    FROM
        Booking
    WHERE
        Booking.RouteID = Route.RouteID)

其他大多数答案都应该有效,但我更喜欢使用EXISTS,因为这是它的目的。

答案 4 :(得分:0)

您可以使用设置操作

 SELECT RouteID  FROM Route
 MINUS
 SELECT RouteId FROM Booking