简体   繁体   English

SQL-如何使用联接在同一表上执行交集(带有子查询)?

[英]SQL - how to perform an intersection on the same table (with a subquery) using joins?

I have two tables. 我有两张桌子。 Car table, and rental table. 汽车表和出租表。

Car: 汽车:

id brand
--------
0  honda
1  yota

Rental: 租金:

id id_car start end
--------
1  1      1     2
2  1      2     NULL

I need to execute two queries. 我需要执行两个查询。 One that shows all cars that are rented. 一个显示所有已租用汽车的视图。 The other that shows all cars that are NOT rented. 另一个显示所有未租用的汽车。

The first query was easy for me. 第一个查询对我来说很容易。

SELECT car.id, car.brand, reg.start, reg.end
FROM car
LEFT JOIN car_registration AS reg ON car.id = reg.id_car
WHERE reg.end IS NULL

The reverse query (for determining rented cars) would involve something along the lines of the opposite. 反向查询(用于确定租车)将涉及相反的内容。 Find a list of rentals, where reg.id_car = car.idm where reg.end IS NOT NULL. 查找租金列表,其中reg.id_car = car.idm,其中reg.end不为空。 However, if an entry exists in the same table where reg.end IS NULL, then the car is actually rented. 但是,如果在reg.end为NULL的同一表中存在一个条目,则实际上是在租车。 I need to intersect a list of car rentals where reg.end IS NULL and renteals where reg.end IS NOT NULL. 我需要与reg.end为NULL的租车列表和reg.end为NOT NULL的Renteals相交。

Pseudo-sql would be something like this. 伪sql将是这样的。

Select DISTINCT car.id (so that duplicate historical rentals are not returned), join with car rentals table, where reg.end is NOT NULL. 选择DISTINCT car.id(这样就不会返回重复的历史租金),并与reg.end为NOT NULL的汽车租赁表合并。 This would give me all cars that are not rented (expired rentals). 这将给我所有未租用的汽车(租期届满)。 However, I need to intersect this with a list of car rentals where reg.end IS null, in order to determine that the car is in-fact not rented. 但是,我需要将其与reg.end为null的汽车租赁列表相交,以确定该汽车实际上没有被租赁。

I know SQL doesn't have an intersect statement. 我知道SQL没有相交语句。 I get how joins work in principle, but this is confusing the hell out of me. 我知道联接的工作原理,但这使我感到困惑。 Any ideas? 有任何想法吗?

You can get both rented and unrented cars in a single query by simply left joining the car table against a subselect where you determine cars that are currently rented out. 只需将车表与子选择(在其中确定当前已出租的车)对接起来,就可以在单个查询中同时获得租用和未租用的汽车。

SELECT
    c.id AS id,
    c.brand AS brand,
    r.rented AS rented
FROM
    (
        SELECT
            id,
            brand
        FROM car
    ) AS c
LEFT JOIN
    (
        SELECT DISTINCT
            id_car,
            1 AS rented
        FROM car_registration
        WHERE `end` IS NULL
    ) AS r
ON c.id = r.id_car

All rows where you have 1 for rented would signify cars that are currently being rented out. 您有1rented行将表示当前正在出租的汽车。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM