首页 文章

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

提问于
浏览
1

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

表格为CAR和SPACE,关系是“一对多”(N个空间中1个CAR; 1个空间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 回答

  • 3

    您在 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
    
  • 5

    您可以使用 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)
    

相关问题