1

So I have two tables using MySql; Owners and Cars, where an owner has a birthdate and the cars have mileage records. The tables look kinda like this:

Owners:
+-------+--------------+
| Field | Type         |
+-------+--------------+
| id    | varchar(10)  |
| birth | datetime     |
| name  | varchar(100) |
+-------+--------------+

Cars:
+--------------+-------------+
| Field        | Type        |
+--------------+-------------+
| plate        | varchar(6)  |
| mileage      | int(11)     |
| owner*       | varchar(10) | //fk references Owners
+--------------+-------------+

I want to get to get the youngest owner and their mileage selected using SQL. I've managed to get the car of the owner being the youngest, but I don't know how I could like JOIN the tables and create a table containg the Owner-attributes AND the mileage-attribute from their car.

SELECT * 
FROM Cars 
WHERE owner = (SELECT id 
               FROM Owners 
               WHERE birth = (SELECT MAX(birth) FROM Owners));

Which I said returns the car e.g.

+--------+---------+------------+
| plate  | mileage | owner      |
+--------+---------+------------+
| KFO405 |    8109 | 9912218527 |
+--------+---------+------------+

But I want it like this:

+------------+---------------------+-----------------------+------------+
| id         | birth               | name                  | milage     |
+------------+---------------------+-----------------------+------------+
| 9912218527 | 1999-12-21 00:00:00 | Marva Rocha           |       8109 |
+------------+---------------------+-----------------------+------------+

Any help is appreciated!

Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
Jesper
  • 2,044
  • 3
  • 21
  • 50

2 Answers2

2

To get the youngest owner and mileage

  SELECT A.ID, A.BIRTH, A.NAME, B.MILAGE
  FROM Owners A
      INNER JOIN Cars B
      ON A.ID=B.owner
  ORDER BY A.birth ASC LIMIT 1;
Bibin Mathew
  • 455
  • 3
  • 11
1

You basically join the tables first and then define the criteria (Birth):

SELECT Owners.name,
       Owners.birth,
       Cars.plate,
       Cars.milage
FROM Owners
JOIN Cars ON Cars.owner = Owners.id
WHERE Owners.birth =
        (SELECT MAX(birth)
         FROM Owners)
Jan Zeiseweis
  • 3,718
  • 2
  • 17
  • 24