仅返回最后一行LEFT JOIN

时间:2014-03-24 07:16:38

标签: mysql sql left-join greatest-n-per-group

SELECT DISTINCT msg.userid, msg.messages, user.fullname, prof.path
FROM messages AS msg
LEFT JOIN users AS user ON msg.userid = md5( user.userid )
LEFT JOIN profile AS prof ON msg.userid = prof.userid
ORDER BY msg.date ASC
LIMIT 0 , 30

上面的代码正在运行,但问题是结果有重复的值:

userid | messages | fullname | path
985434 | hello... | Foo Bar  | /path/to/hello.jpg
985434 | hello... | Foo Bar  | /path/to/new.jpg

问题是PATH如何将path的结果限制在最近?或者每个全名只有一个?...它杀了我谢谢你的理解。

2 个答案:

答案 0 :(得分:2)

您可以使用GROUP_CONCAT()所有路径,并使用群组中的SUBSTRING_INDEX()选择第一条路径,您也可以在GROUP_CONCAT( prof.path order by some_col DESC )中使用订单

SELECT 
 msg.userid,
 msg.messages, 
 user.fullname, 
SUBSTRING_INDEX(GROUP_CONCAT( prof.path ),',',1) AS path
FROM messages AS msg
LEFT JOIN users AS USER ON msg.userid = MD5( user.userid )
LEFT JOIN profile AS prof ON msg.userid = prof.userid
GROUP BY msg.userid
ORDER BY msg.date ASC
LIMIT 0 , 30

答案 1 :(得分:1)

您要做的是选择用户消息。您还希望为每条消息选择一个路径。以下是如何执行此操作的示例:

SELECT msg.userid, msg.messages, users.fullname, 
  (select max(path) from profile where profile.userid = msg.userid) as maxpath
FROM messages AS msg
LEFT JOIN users ON msg.userid = md5( users.userid )
ORDER BY msg.date ASC;

您还可以使用group_concat而不是max来获取所有路径的列表。此外,子选择可能更复杂,例如查找最后日期(假设该表中有日期信息)。

为什么顺便将外连接用户留给邮件?是否有没有关联用户的消息?