[英]SQL getting max id field on a LEFT JOIN
I am trying to pull the photo from tblimage that corresponds to the maxid in the tblimage for each user. 我试图从tblimage中拉出与每个用户的tblimage中的maxid相对应的照片。 Currently, I am getting all the messages from the message table and a random photo for the user that posted the message, I would like the photo to be the latest uploaded photo.
目前,我收到消息表中的所有消息和发布消息的用户的随机照片,我希望照片是最新上传的照片。 the way its written now it just pulls a random photo from the table.
它现在写的方式只是从表中拉出一张随机照片。 any suggestions?
有什么建议?
table structures are as such: 表结构如下:
messages: msgid, message, user_id, event_id
消息:msgstr,message,user_id,event_id
tblimage: id, photo, useridtblimage:id,photo,userid
SELECT messages.*, tblimage.photo, max(tblimage.id)
FROM messages LEFT JOIN tblimage ON messages.user_id = tblimage.userid
GROUP BY messages.msg_id, messages.user_id
ORDER BY messages.msg_id DESC, tblimage.id desc
Try 尝试
SELECT messages.*, T2.photo
FROM messages
LEFT JOIN (SELECT userid, MAX(id) AS maxid
FROM tblimages
GROUP BY userid) AS T1
ON messages.user_id = T1.userid
LEFT JOIN tblimages AS T2
ON T2.id = T1.maxid
ORDER BY messages.msg_id DESC
which finds max(id) for each user in tblimages, then uses that to join each user to the latest photo for that user. 在tblimages中找到每个用户的max(id),然后使用它将每个用户加入该用户的最新照片。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.