如何选择不参与联接的记录

时间:2015-12-30 20:20:08

标签: mysql sql database select

我需要创建一个返回一些不参与连接的记录的查询,我粘贴所涉及的表和我写的查询。

表格为CAR和SPACE,关系为“一对多”(N个空间中1个CAR; 1个SPACE 1 CAR中)

汽车记录表:

........................................
car_id  | mark    | model   | prize
........................................
    1   | fiat    | 500     | 15000
    2   | fiat    | panda   | 8000
    3   | opel    | astra   | 20000
    4   | renault | clio    | 14000
    5   | opel    | corsa   | 12000
    6   | fiat    | panda   | 8000
    7   | fiat    | 500     | 15000
    8   | renault | capture | 16000
    9   | renault | clio    | 14000
    10  | fiat    | 500     | 15000

SPACE TABLE的记录(主键由row,column和room_id标识.car_id是CAR表的主键的外键):

..................................................
   row  | column  | room_id | dimension | car_id
..................................................
    1   | 1       | 1       | 100       | 1
    1   | 2       | 1       | 100       | 1
    1   | 3       | 1       | 100       | NULL
    2   | 1       | 1       | 100       | 1
    2   | 2       | 1       | 100       | 1
    2   | 3       | 1       | 100       | NULL
    3   | 1       | 1       | 100       | NULL
    3   | 2       | 1       | 100       | 6
    3   | 3       | 1       | 100       | 6

现在,我想从查询中得到的是选择所有不在任何空间的汽车。我希望结果是那个表:

........................................
car_id  | mark    | model   | prize
........................................
    2   | fiat    | panda   | 8000
    3   | opel    | astra   | 20000
    4   | renault | clio    | 14000
    5   | opel    | corsa   | 12000
    7   | fiat    | 500     | 15000
    8   | renault | capture | 16000
    9   | renault | clio    | 14000
    10  | fiat    | 500     | 15000

这是我写的查询,但它没有返回我期望的结果。

SELECT car.* FROM car,space WHERE car.car_id = space.car_id AND space.car_id IS NULL

我最近才学习数据库的逻辑,不幸的是我不好,查询完全错误,但我不知道如何纠正它。

2 个答案:

答案 0 :(得分:5)

您在where子句中使用了冲突的术语:

WHERE car.car_id = space.car_id AND space.car_id IS NULL

space.car_id不能同时为null且匹配car.car_id

您正在寻找左连接:

SELECT  *
FROM    car
LEFT JOIN
        space
ON      car.car_id = space.car_id
WHERE   space.car_id IS NULL

答案 1 :(得分:3)

您可以使用not in检查不在空间表中的汽车中的汽车ID。由于空格表的car_id列中包含null值,因此where子句会将其过滤掉。

SELECT car.* FROM car
where car_id not in (select distinct car_id from space where car_id is not null)

或者更好地使用not exists

SELECT c.* FROM car c
where not exists (select 1 from space where car_id = c.car_id)