【问题标题】:Joining versus Union on two MySQL tables with GROUP BY and ORDER BY conditions使用 GROUP BY 和 ORDER BY 条件在两个 MySQL 表上加入与联合
【发布时间】:2013-09-06 23:45:25
【问题描述】:

我正在尝试组合按 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)

【问题讨论】:

  • UNION ALL 可能会完成这项工作
  • @tim 我已经尝试过这个的变体:SELECT chat.threadid, messages.threadid, chat.uidto, messages.uidto, chat.uidfrom, messages.uidfrom, chat.last_activity, messages.last_activity, chat.last_message, messages.last_message FROM messages LEFT JOIN chat GROUP BY threadid ORDER BY last_message; 还没有成功
  • @Mihai UNION ALL 仍然给我排序问题。它在抱怨模棱两可的表格。
  • 排序有什么问题?

标签: php mysql database


【解决方案1】:
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

【讨论】:

  • 已编辑,试一试。
  • 好吧,这似乎可行,但结果是我没有意识到会发生。由于聊天和消息表可能具有相同的线程 ID,因此将它们组合在一起。有没有办法通过查询将它们分开,或者你认为最好确保两个表之间的线程ID是唯一的。
  • 对于一个连接,最好有唯一的线程,同时让线程本身是唯一的。你应该有一个具有唯一自动增量字段的新表。
  • 我注意到,如果我运行查询并且聊天中有线程 ID 3 而消息中没有 3,则聊天中的 3 将不会显示。有什么办法可以确保所有线程都被考虑在内?
  • 当我将 JOIN 更改为 RIGHT JOIN 时,它似乎在聊天表中看到 threadid 3 但列显示为 NULL。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多