我想这就是你所说的。
mysql> create table messages (ts_send int, message char(30), id int);
Query OK, 0 rows affected (0.01 sec)
mysql> create table conversations (id int);
Query OK, 0 rows affected (0.01 sec)
现在一些数据。
mysql> insert into conversations values ( 1), (2), (3), (4);
Query OK, 4 rows affected (0.00 sec)
Records: 4 Duplicates: 0 Warnings: 0
mysql> insert into messages values ( 4, 'abc', 1 ),
(5, 'pqr', 1),
(4, 'abc', 2),
(5, 'abc', 3),
(6, 'abc', 4);
Query OK, 5 rows affected (0.01 sec)
Records: 5 Duplicates: 0 Warnings: 0
然后是查询。
mysql> select messages.id, message, ts_send
from messages
where ROW(id, ts_send) in
(select messages.id, max(ts_send)
from messages, conversations
where messages.id = conversations.id group by id);
+------+---------+---------+
| id | message | ts_send |
+------+---------+---------+
| 1 | pqr | 5 |
| 2 | abc | 4 |
| 3 | abc | 5 |
| 4 | abc | 6 |
+------+---------+---------+
4 rows in set (0.00 sec)
mysql>
对?
*对此进行了编辑,以反映 Marty McVry 的评论。