我有一个存储user_avatar文件路径的表:
id | userid | file | last_update |
1 | 23 | myphoto.png | x_timestamp |
2 | 23 | myphoto2.png | x_timestamp |
3 | 25 | myavatar.png | x_timestamp |
我有一个返回user_score的表:
id | gamerid | score | last_update |
1 | 23 | 44 | x_timestamp |
2 | 25 | 99 | x_timestamp |
这是我用来显示用户分数及其头像的查询
SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
以上查询将为用户23返回2个重复行,因为他在user_avatar表中下载了2张不同的照片。现在它的输出是这样的:
GAMER SCORES RESULTS
myphoto.png | 44
myphoto2.png | 44
myavatar.png | 99
实际上,每个用户仅返回一行,并且最后下载的头像应用作主头像。我该如何解决?
您应该选择最新头像的值..可能与user_id的最大ID相关联
SELECT ua.*, us.*
FROM user_score us
INNER JOIN (
select user_id, max(id) max_id
from user_avatar
) t on t.user_id = us.user_id
LEFT JOIN user_avatar ua
ON us.gamerid=ua.u serid
AND t.max_id = ua.id
实际上是最后的头像头像
您可以在下面尝试-
SELECT * FROM user_score us LEFT JOIN user_avatar ua ON us.gamerid=ua.userid
and ua.last_update =
(select max(last_update) from user_avatar ua1 where ua.userid=ua1.userid)