mysql LEFT JOIN主表和另外两个表,每个表都有最大值

时间:2018-12-01 18:25:55

标签: mysql sql

所以我有三个表:

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的用户获取单行结果,该结果满足:

  • 用户表中的所有内容
  • 该用户的最新条目的黄金值(users_id = 1,created_at = MAX)
  • Extra表中最大的val4,其中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技能而已是这里的问题。

谢谢!

2 个答案:

答案 0 :(得分:0)

只需使用子查询:

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

答案 1 :(得分:0)

我将使用以下子查询:

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 ;