mysql左连接主表和两个附加表,每个表的最大值为

beq87vna  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(274)

所以我有三张table:

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  |
+----+------------+-----+

因此,我希望(在单个查询中)为id=1的用户获得一个单行结果,该结果包含:
用户表中的所有内容
该用户的最新条目的gold值(users\u id=1,created\u at=max)
额外表中的最大值4,其中users_id=1
因此结果行如下所示:

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

我可以把第一部分做完

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

第二部分是

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

但不管我怎么努力我都不能把它们结合起来。。。我真的很想在单个查询中完成这项工作,显然我可以用多个查询来完成这项工作——但我相信这只是我缺乏mysql技能的问题。
谢谢!

ruyhziif

ruyhziif1#

只需使用子查询:

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

这是users连接的子查询。id:

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

eit6fx6z2#

我将使用如下子查询:

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 ;

相关问题