1

我正在尝试组合按 threadid 分组并按 last_activity 排序的消息和聊天表。当我尝试使用 UNION 时,我遇到了排序问题,所以我假设加入会做得更好。我在语法上有问题,希望得到一些指导。以下是我正在使用的两个选择。非常感谢任何帮助。

从消息表中选择:

mysql> select threadid, uidto, uidfrom, last_activity, last_message from messages group by threadid order by last_activity DESC;
+----------+-------+---------+---------------------+------------------+
| threadid | uidto | uidfrom | last_activity       | last_message     |
+----------+-------+---------+---------------------+------------------+
|        2 |     2 |       1 | 2013-09-06 22:59:38 | blurred lines... |
|        1 |     9 |       1 | 2013-09-06 22:49:16 | kisses!          |
+----------+-------+---------+---------------------+------------------+
2 rows in set (0.00 sec)

从聊天表中选择:

mysql> select threadid, uidto, uidfrom, last_activity, last_message from chat group by threadid order by last_activity DESC;
+----------+-------+---------+---------------------+--------------+
| threadid | uidto | uidfrom | last_activity       | last_message |
+----------+-------+---------+---------------------+--------------+
|        2 |     2 |       1 | 2013-09-06 23:03:27 | danke        |
|        1 |     1 |       9 | 2013-09-06 22:30:34 | much         |
+----------+-------+---------+---------------------+--------------+
2 rows in set (0.00 sec)
4

1 回答 1

0
select m.threadid, m.uidto, m.uidfrom, m.last_activity, m.last_message,
c.threadid, c.uidto, c.uidfrom, c.last_activity, c.last_message
FROM messages m
JOIN chat c on m.threadid=c.threadid 
GROUP by threadid ORDER BY last_message


(select m.threadid, m.uidto, m.uidfrom, m.last_activity, m.last_message FROM messages m
UNION ALL
select c.threadid, c.uidto, c.uidfrom, c.last_activity, c.last_message FROM chat c)
GROUP by threadid ORDER BY last_message
于 2013-09-06T23:58:27.900 回答