I am having problems selecting items from a table where a device_id can be either in the from_device_id column or the to_device_id column. I am trying to return all chats where the given device is ID is in the from_device_id or to_device_id columns, but only return the latest message.
select chat.*, (select screen_name from usr where chat.from_device_id=usr.device_id limit 1) as from_screen_name, (select screen_name from usr where chat.to_device_id=usr.device_id limit 1) as to_screen_name from chat where to_device_id="ffffffff-af28-3427-a2bc-83865900edbe" or from_device_id="ffffffff-af28-3427-a2bc-83865900edbe" group by from_device_id, to_device_id;
+----+--------------------------------------+--------------------------------------+---------+---------------------+------------------+----------------+ | id | from_device_id | to_device_id | message | date | from_screen_name | to_screen_name | +----+--------------------------------------+--------------------------------------+---------+---------------------+------------------+----------------+ | 20 | ffffffff-af28-3427-a2bc-83860033c587 | ffffffff-af28-3427-a2bc-83865900edbe | ee | 2011-02-28 12:36:38 | kevin | handset | | 1 | ffffffff-af28-3427-a2bc-83865900edbe | ffffffff-af28-3427-a2bc-83860033c587 | yyy | 2011-02-27 17:43:17 | handset | kevin | +----+--------------------------------------+--------------------------------------+---------+---------------------+------------------+----------------+ 2 rows in set (0.00 sec)
As expected, two rows are returned. How can I modify this query to only return one row?
mysql> describe chat; +----------------+---------------+------+-----+-------------------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------------+---------------+------+-----+-------------------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | from_device_id | varchar(128) | NO | | NULL | | | to_device_id | varchar(128) | NO | | NULL | | | message | varchar(2048) | NO | | NULL | | | date | timestamp | YES | | CURRENT_TIMESTAMP | | +----------------+---------------+------+-----+-------------------+----------------+ 5 rows in set (0.00 sec)
You need to tell SQL that it should sort the returned data by date to get the most recent chat. Then you just limit the returned rows to 1.