Question

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

The above code is working but the problem is that the result has duplicate values:

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

The problem is the PATH. How to limit the result of path into the most recent? or only one per fullname?...It's killing me Thank you for understanding.

Was it helpful?

Solution 2

What you want to do is select users messages. You also want to select one path per message. Here is an example on how to do this:

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;

You can also use group_concat instead of max, to get a list of all paths. Also the sub select can be more complex, with looking for the last date for instance (provided there is a date information in that table).

Why do you left outer join users to messages by the way? Are there messages without associated users?

OTHER TIPS

You can do so by using GROUP_CONCAT() all the paths and using SUBSTRING_INDEX() on the group to pick first path you can also use order by in GROUP_CONCAT( prof.path order by some_col DESC ) like

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top