简体   繁体   中英

mysql LEFT JOIN main table and two additional tables with max value from each

So i have three tables:

Users
+-------+-----+----+
| id    | val1|val2|
+-------+-----+----+
| 1     |  1  |3   |
| 2     |  2  |5   |
| 3     |  4  |7   |
+-------+-----+----+

UsersData
+----+--------------+------------+-----|
| id | users_id     | created_at | gold|
+----+--------------+------------+-----|
|  9 |  1           |121454561212| 14  |
|  10|  1           |131454561212|  2  |
|  11|  2           |111454561212| 99  |
+----+--------------+------------+-----+

Extra
+----+------------+-----|
| id | users_id   | val4|
+----+------------+-----|
|  1 |  1         |  5  |
|  2 |  1         |  6  |
|  3 |  1         |  7  |
+----+------------+-----+

So what i wish to achieve(in a single query) is to get a single row result for user with id = 1, that holds:

  • everything from Users Table
  • gold value of the most recent entry for that user (users_id = 1, created_at = MAX)
  • biggest val4 from the Extra table, where users_id = 1

So the result row would look like this:

+-------+-----+----+-----+----+
| id    | val1|val2|gold |val4|
+-------+-----+----+-----+----|
| 1     |  1  |3   | 2   |  7 |
------------------------------+

I can get The first part done with

SELECT Users.id, Users.val1, Users.val2, UsersData.gold
FROM UsersData
LEFT JOIN Users ON UsersData.users_id = Users.id
WHERE Users.id = 1 
ORDER BY UsersData.created_at DESC
LIMIT 1

and the second part with

SELECT MAX(Distances.distance) AS maxdistance FROM Distances WHERE Distances.users_id = 1

But i can't combine them no matter how i try... I would really like to have this done in single query, obviously i can do it with multiple - but i believe it is just my lack of mysql skills that is the issue here.

Thanks!

Just use subquery:

SELECT Users.id, Users.val1, Users.val2, UsersData.gold,
(SELECT MAX(Distances.distance) FROM Distances WHERE Distances.users_id = Users.id) AS maxdistance
FROM UsersData
RIGHT JOIN Users ON UsersData.users_id = Users.id
WHERE Users.id = 1 
ORDER BY UsersData.created_at DESC
LIMIT 1

This is subquery connected by Users.id:

SELECT MAX(Distances.distance) FROM Distances WHERE Distances.users_id = Users.id) AS maxdistance

I would use subqueries like this:

select u.*,
       (select ud.gold
        from userdata ud
        where ud.users_id = u.id
        order by ud.created_at desc
        limit 1
       ) as most_recent_gold,
       (select max(e.val4)
        from extra e
        where e.users_id = u.id
       ) as max_val4
from users u
where u.id = 1 ;

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