SELECT DISTINCT values ​​after JOIN

I have 3 tables:

Vehicle: vehicle_id, vehicle_type
1, motorcycle
2, car
3, van

Owners: person_id, vehicle_id, date_bought
1, 1, 2009
1, 2, 2008
2, 3, 2009
2, 1, 2005

I want to display a list of all vehicle names. If you also need to return person_id = 1, date_bought.

So, I thought I would start with this:

SELECT * FROM vehicles
LEFT JOIN Owners USING (vehicle_id)

which returns this:

1, 1, motorcycle, 2009
1, 2, car, 2008
2, 3, van, 2009
2, 1, motorcycle, 2005

However, now I can not narrow it down to the desired result. If I use DISTINCT(car_id), there are no changes, as I already select individual car identifiers before JOIN; they do not differ after association. If I use WHERE person_id = 1, I delete the last 2 lines and the whole link to the van is gone. If I use GROUP BY car_id, the first and last lines are combined, and date_boughtfor a motorcycle is chosen arbitrarily. I want it:

1, 1, motorcycle, 2009
1, 2, car, 2008
 , 3, van, 

, JOIN . JOIN?

+3
2

. , , , , .

SELECT person_id, vehicles.* 
FROM vehicles 
LEFT OUTER JOIN Owners on vehicles.vehicle_id = owners.vehicle_id 
and person_id = 1
+5

, :

   SELECT DISTINCT
          o.person_id,
          v.vehicle_id,
          v.vehicle_type,
          o.date_bought
     FROM VEHICLES v
LEFT JOIN OWNERS o ON o.vehicle_id = v.vehicle_id
LEFT JOIN (SELECT t.vehicle_id,
                  MAX(t.date_bought) 'max_date_bought'
            FROM OWNERS t
        GROUP BY t.vehicle_id) x ON x.vehicle_id = o.vehicle_id
                                AND x.max_date_bought = o.date_bought
    WHERE o.person_id IS NULL 
       OR o.person_id = 1

, - OWNERS NULL, OWNERS vehicle_id.

+2

Source: https://habr.com/ru/post/1726312/


All Articles