Essentially what I want to do is select the most recent message between one user anyone they either received or sent a message to. This means that the unique user id I need could be either in the m_to or m_from. So how can I filter a search to select a unique id from one of two fields, where the field is not the main user’s id? Am I making sense here?
SELECT * FROM messages
WHERE m_to = '$user_id' OR m_from = '$user_id'
ORDER BY date
So just to (try to) be clear, I need to make a query that will select the most recent message either received or sent from the main user for every user they’ve received or sent a message to. This way there aren’t duplicated users in the list. However since this could either be in the to or from field, I have no clue how to do this. Can anyone lend me a hand here?
EDIT: Okay, apparently I wasn’t clear. the $user_id variable is the user id of the logged in user. Meaning I need unique messages from either the m_from or m_to field which is NOT $user_id
EDIT:
If we’re running this query…
SELECT
the_user,
the_other_party,
MAX(date) AS max_date
FROM (
SELECT
CASE m_to WHEN ‘IxjXgC’ THEN m_to ELSE m_from END AS the_user,
CASE m_from WHEN ‘IxjXgC’ THEN m_to ELSE m_from END AS the_other_party,
date
FROM messages
WHERE m_to = ‘IxjXgC’
OR m_from = ‘IxjXgC’
) m
and let’s say we have these categories in the database…
m_to m_from date
IxjXgC ShJiMr 2012-01-22 01:20:37
ShJiMr IxjXgC 2012-01-22 02:22:37
LhJiM1 IxjXgC 2012-01-22 03:23:37
and I run the query above, then the result becomes…
the_other_party date
ShJiMr 2012-01-22 03:23:37
I will not accuse you of being lazy (I’m no better than you in that regard, I’m afraid), but I’ll agree with Andreas Rohde in that you should exert yourself to listing the necessary columns explicitly as often as possible. Doing so may really help you to see solutions that otherwise would be less obvious, if at all.
Take your present problem, for instance. You need a sort of GROUP BY query that would disregard a user’s status as a sender/receiver. Why, you could simply substitute sender for receiver and vice versa, in once case, and leave them unchanged in the other. Consider this then:
The result set will contain rows where the user in question will always be returned as
the_user, and the other party, well, asthe_other_party.Of course, since we made sure that
'$user'is returned in the same column, the first CASE can be got rid of:That is, if you need that column at all.
Anyway, you can now aggregate the result set of the above query, e.g. like this:
You can also join the last query as a subselect back to
messageson(messages.m_to = agg.the_user OR messages.m_from = agg.the_user) AND messages.date = agg.max_dateto get the rest of the columns.