我已经能够选择附加了消息的所有会话,但我无法确定它是最新的消息。请解释查询无效的原因。我试图避免使用子查询或将表连接到自己。
DESC ir_chats;
+-----------------+------------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+------------------+------+-----+-------------------+----------------+
| chat_id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| creator_user_id | int(11) | NO | MUL | NULL | |
| friend_user_id | int(11) | NO | MUL | NULL | |
| created | timestamp | NO | | CURRENT_TIMESTAMP | |
+-----------------+------------------+------+-----+-------------------+----------------+
4 rows in set (0.00 sec)
Desc ir_chat_messages;
+-------------+-----------------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------------------+------+-----+-------------------+-------+
| chat_id | int(10) unsigned | NO | MUL | NULL | |
| user_id | int(11) | NO | MUL | NULL | |
| created | timestamp | NO | | CURRENT_TIMESTAMP | |
| read_status | enum('read','unread') | NO | | unread | |
| message | text | NO | | NULL | |
+-------------+-----------------------+------+-----+-------------------+-------+
SELECT * FROM ir_chats;
+---------+-----------------+----------------+---------------------+
| chat_id | creator_user_id | friend_user_id | created |
+---------+-----------------+----------------+---------------------+
| 1 | 100 | 200 | 2014-10-15 18:06:54 |
+---------+-----------------+----------------+---------------------+
1 row in set (0.00 sec)
SELECT * FROM ir_chat_messages;
+---------+---------+---------------------+-------------+--------------------------+
| chat_id | user_id | created | read_status | message |
+---------+---------+---------------------+-------------+--------------------------+
| 1 | 100 | 2014-10-15 18:16:06 | | This is a message. |
| 1 | 200 | 2014-10-15 18:26:59 | | This is another message. |
+---------+---------+---------------------+-------------+--------------------------+
2 rows in set (0.00 sec)
SELECT ir_chats.chat_id, ir_chat_messages.created, ir_chat_messages.message
FROM ir_chat_messages
JOIN ir_chats USING (chat_id)
GROUP BY ir_chats.chat_id
ORDER BY ir_chat_messages.created DESC;
+---------+---------------------+--------------------+
| chat_id | created | message |
+---------+---------------------+--------------------+
| 1 | 2014-10-15 18:16:06 | This is a message. |
+---------+---------------------+--------------------+
1 row in set (0.00 sec)
我问是否有办法在没有子查询或加入另一个表的情况下执行此操作。你说这不可能吗?随附的“重复”帖子没有回答我的问题。