0

I have 3 tables. Users, addresses and countries.

I want all rows from users table, order by DESC. Also in the addresses table, I want the last address row of the users. and I want the country name row of the user address from the countries table.

users

| id  | user_name | first_name | last_name | email          |
| --- | --------- | ---------- | --------- | -------------- |
| 1   | john      | John       | Doe       | john@email.com |
| 2   | jane      | Jane       | Doe       | jane@email.com |
| 3   | jack      | Jack       | Doe       | jack@email.com |

addresses

| id | user_id | phone      | address               | country_id |
| -- | ------- | ---------- | --------------------- | ---------- |
| 1  | 1       | 1122334455 | 1442 Carroll Via      | 1          |
| 2  | 1       | 2233445566 | 04233 Mayert Motorway | 3          |
| 3  | 2       | 3445664324 | 61235 Kristina Greens | 2          |
| 4  | 2       | 52547858   | 42781 Borer Knoll     | 4          |
| 5  | 3       | 88557755   | 2578 Ericka Motorway  | 5          |

countries

| id  | country_name |
| --- | ------------ |
| 1   | England      |
| 2   | France       |
| 3   | Germany      |
| 4   | Spain        |
| 5   | Denmark      |

Result Join Table I want is

| user_name | email          | address_id | address               | phone      | country_id | country_name |
|-----------|----------------|------------|-----------------------|------------|------------|--------------|
| jack      | jack@email.com | 5          | 2578 Ericka Motorway  | 88557755   | 5          | Denmark      |
| jane      | jane@email.com | 4          | 42781 Borer Knoll     | 52547858   | 4          | Spain        |
| john      | john@email.com | 2          | 04233 Mayert Motorway | 2233445566 | 1          | Germany      |

I have tried a lot but not getting result

SELECT * FROM users u
LEFT JOIN addresses a ON a.user_id = u.id
LEFT JOIN countries c ON c.id = a.country_id
GROUP BY u.id
ORDER BY u.id DESC
SELECT * FROM users u
LEFT JOIN (SELECT * FROM addresses ORDER BY id DESC) a ON a.user_id = u.id
LEFT JOIN countries c ON c.id = a.country_id
GROUP BY u.id
ORDER BY u.id DESC

I tried many sql queries. I couldn't find the solution. I also tried the "max(id)" function in one of the queries. I couldn't get the result either.

Thanks in advance to anyone who can help me find the right query.

  • Join with a subquery that gets the last row for each user. See https://stackoverflow.com/questions/1313120/retrieving-the-last-record-in-each-group-mysql?rq=1 for how to write this subquery. – Barmar Jul 28 '23 at 15:35

0 Answers0