I have some messages and a current user.
Messages have an id
, users have an id
.
I want to get a list of (unique) user ids where:
The first user id
is for the user who sent the message to the current user with the highest message id
and all the message ids for the last user id are lower than that of any other user who sent the current user a message.
So far I am able to get a list of users who sent the current user a message 开发者_开发知识库with:
"SELECT sender_id AS messgr_id FROM messages
WHERE receiver_id = '$curr_id'
UNION SELECT receiver_id AS messgr_id FROM messages
WHERE sender_id = '$curr_id' ";
but I am stuck as to the best way to order it in the way i want (i am learning SQL as i do this and so im no expert :))
Thanks!
something like this should do the trick
SELECT *
FROM (
SELECT sender_id AS messgr_id FROM messages
WHERE receiver_id = '$curr_id'
UNION SELECT receiver_id AS messgr_id FROM messages
WHERE sender_id = '$curr_id'
) T1
GROUP BY messgr_id
ORDER BY messgr_id DESC
That will give you a list of user ids with duplicates eliminated, and sorted high-to-low.
Update:
Re-reading your question, it sounds like you're looking for a list of user id's ordered by message id -- which isn't currently shown in your example. Assuming that your messages
table has an id
column (in addition to receiver_id
and sender_id
), here's how you would do that:
SELECT messgr_id, max(message_id) as max_message_id
FROM (
SELECT sender_id AS messgr_id, id as message_id FROM messages
WHERE receiver_id = '$curr_id'
UNION SELECT receiver_id AS messgr_id, id as message_id FROM messages
WHERE sender_id = '$curr_id'
) T1
GROUP BY messgr_id
ORDER BY max_message_id DESC
i'm not sure but i think you only want to order your SELECTion?
"SELECT sender_id AS messgr_id FROM messages
WHERE receiver_id = '$curr_id'
ORDER BY sender_id
UNION SELECT receiver_id AS messgr_id FROM messages
WHERE sender_id = '$curr_id'
ORDER BY sender_id DESC";
精彩评论