简体   繁体   中英

Combination of table left join to an inner join in mysql

Lets say, I have 3 tables, cars, cars_owner and owner. Now I want to have the complete list of cars, those that do have owners and those that don't.

When a car has an own, I must have the data of the owner.

Wrong query 1 (selects ownerless cars out): 
SELECT * FROM car 
LEFT JOIN cars_owner ON ...
INNER JOIN owner ON ...

Wrong query 2 (selects cars_owner relations without owners too): 
SELECT * FROM car 
LEFT JOIN cars_owner ON ...
LEFT JOIN owner ON ...

The question ist: How to left join a table with an inner join in mysql? Any ideas?

This Query returns the cars that have owners:

SELECT * FROM car
LEFT JOIN cars_owner ON (car.CarID=cars_owner.CarID)
inner join owner ON (owner.OwnID = cars_owner.OwnID)

However this returns the cars without owners:

SELECT * FROM car
where (car.CarID!=(SELECT car.CarID FROM car
                   LEFT JOIN cars_owner ON (car.CarID=cars_owner.CarID)
                   inner join owner ON (owner.OwnID = cars_owner.OwnID)) )

You just need to nest the JOINs correctly:

SELECT * FROM car 
LEFT JOIN (cars_owner INNER JOIN owner ON cars_owner.owner_id = owner.owner_id
          ) ON car.car_id = cars_owner.car_id

The point is that you want all cars (so a left join on cars_owner), but only cars_owner that have an existing owner (so an inner join on owner).

The brackets make sure that the inner join is executed first. That is: Give me all cars, and from those car_owners that have an actual owner, show the owners (otherwise show them as NULL, but don't discard the whole car row).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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