I have a "message" table where users send and receive messages, quite straightforwardly. What I would like to do is: retrieve DISTINCT sender_ids WHERE receiver_id is X, and sort it so that users from recipient X have unread messages, and users after recipient X has read the messages will appear after and everything will be sort by created_at DESC.
Any ideas how I can do this? Note. Performance is also a problem.
This is a query that I used, but it looks like the sorting is not really doing right, maybe DISTINCT is screwing things up? I expect a result of 6, 5, 4, 2, 3 - but I get 6, 5, 4, 3, 2
SELECT DISTINCT sender_id FROM message m WHERE receiver_id = 1 ORDER BY read_at, created_at DESC
Here is a table with sample data:
CREATE TABLE `message` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `sender_id` bigint(20) NOT NULL, `receiver_id` bigint(20) NOT NULL, `message` text, `read_at` datetime DEFAULT NULL, `created_at` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `sender` (`sender_id`), KEY `receiver` (`receiver_id`), KEY `dates` (`receiver_id`,`read_at`,`created_at`) ) ENGINE=MyISAM AUTO_INCREMENT=13 DEFAULT CHARSET=latin1; INSERT INTO `message` (id, sender_id, receiver_id, message, read_at, created_at) VALUES (1,2,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:01'), (2,1,2,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:02'), (3,2,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:03'), (4,3,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:04'), (5,3,1,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:05'), (6,1,4,NULL,'2011-01-01 01:01:01','2011-01-01 01:01:06'), (7,4,1,NULL,NULL,'2011-01-01 01:01:07'), (8,5,1,NULL,NULL,'2011-01-01 01:01:08'), (9,5,1,NULL,NULL,'2011-01-01 01:01:09'), (10,1,6,NULL,NULL,'2011-01-01 01:01:10'), (11,6,1,NULL,NULL,'2011-01-01 01:01:11');