I am trying to make an SQL query from a table - to receive the latest messages from all user pairs with user 36 as the sender or recipient and join them using the users table to get the names. I managed to create something like this, but still want to ask if there are simpler ones | effective solution. Mysql Version - 5.5.31
table: messages fields: sender_user_id, recipient_user_id, date, text
request:
SELECT * FROM (SELECT (CASE sender_user_id > recipient_user_id WHEN true THEN CONCAT(recipient_user_id, '|', sender_user_id) WHEN false THEN CONCAT(sender_user_id, '|', recipient_user_id) END) as hash, sender_user_id, recipient_user_id, date, text, u.first_name FROM fed_messages LEFT JOIN fed_users as u ON ((fed_messages.sender_user_id = 36 AND fed_messages.recipient_user_id = u.id) OR (fed_messages.recipient_user_id = 36 AND fed_messages.sender_user_id = u.id)) WHERE sender_user_id = 36 OR recipient_user_id = 36 ORDER BY date DESC) as main GROUP BY hash;
Thanks. Upd. Data from the table of sample messages:
mysql> SELECT id, sender_user_id, recipient_user_id, text, date FROM federation.fed_messages WHERE id> 257;
-----+----------------+-------------------+-----------------+---------------------+ | id | sender_user_id | recipient_user_id | text | date | +-----+----------------+-------------------+-----------------+---------------------+ | 258 | 40 | 36 | and one more | 2013-06-06 10:57:17 | | 259 | 36 | 38 | another message | 2013-06-06 11:03:49 | | 260 | 38 | 36 | some mes | 2013-06-06 12:29:33 | | 261 | 38 | 36 | message | 2013-06-06 12:29:53 | | 262 | 36 | 38 | message | 2013-06-06 12:47:26 | | 263 | 36 | 40 | some message | 2013-06-10 16:22:46 |
The result should be with identifiers - 262, 263
source share