【问题标题】:MYSQL server: Write a query to display cars which was not taken on rentMYSQL 服务器:编写查询以显示未出租的汽车
【发布时间】:2020-08-25 01:29:51
【问题描述】:

使用 Cars 和 Rentals 表检索记录。

CARScar_id、car_name、car_type)

RENTALSrental_id、cust_id、car_id、pickup_date、km、票价)

SELECT c.car_id, c.car_name, c.car_type 
FROM cars as c, rentals as r
WHERE c.car_id=r.car_id and r.pickup_date=null 
ORDER BY c.car_id;

我试过了,但输出是 NO ROWS SELECTED

【问题讨论】:

  • 使用左连接而不是过时的逗号连接。并将示例数据作为文本添加到问题中
  • 从不FROM 子句中使用逗号。 始终使用正确、明确、标准、可读的JOIN语法。

标签: mysql sql database join select


【解决方案1】:

我会推荐NOT EXISTS 用于此查询:

select c.*
from cars c
where not exists (select 1 from rentals r where r.car_id = c.car_id);

也就是说,您的查询有多个错误:

  • FROM 子句中的逗号非常上世纪。使用JOIN
  • = NULL总是会过滤掉所有行。几乎所有与NULL 的比较都返回NULL,它被视为“假”。正确的比较是IS NULL,但我认为不需要。
  • 您可以使用LEFT JOIN 指定等效逻辑,但我认为NOT EXISTS 更接近问题的陈述。

【讨论】:

    【解决方案2】:

    您最初的意图是连接两个表并过滤连接右侧不匹配的行。这种技术有时被称为反左连接

    您的尝试失败了,因为您需要 left join 而不是(隐式)inner join,并且因为您没有正确检查无效性(这需要运算符 is null)。

    left join 解决方案短语为:

    select c.*
    from cars c
    left join rentals r on r.car_id = c.car_id
    where r.car_id is null
    order by c.car_id
    

    请注意,我在 car_id 列而不是 pickup_date 上检查是否为空 - 任何不可为空的列都可以,但是我发现使用连接列时意图更清晰。

    【讨论】:

      【解决方案3】:

      一个简单的方法是使用NOT IN

      SELECT car_id, car_name, car_type 
      FROM cars
      WHERE car_id NOT IN (SELECT car_id FROM rentals)
      ORDER BY car_id;
      

      【讨论】:

        猜你喜欢
        • 2021-09-09
        • 1970-01-01
        • 2018-07-25
        • 1970-01-01
        • 1970-01-01
        • 2019-06-20
        • 1970-01-01
        • 2016-05-25
        • 2023-01-14
        相关资源
        最近更新 更多