user3204806
user3204806

Reputation: 322

Return Only Last Row LEFT JOIN

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.

Upvotes: 1

Views: 226

Answers (2)

Thorsten Kettner
Thorsten Kettner

Reputation: 94914

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?

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64476

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

Upvotes: 2

Related Questions