【问题标题】:Select where column1 or column2 equal to id, but group by other value of the row选择其中 column1 或 column2 等于 id,但按行的其他值分组
【发布时间】:2015-06-22 17:28:27
【问题描述】:

我有这张表用于用户之间的消息

id |sender |receiver 
--------------------
   |1      |2
   |3      |1
   |1      |4
   |2      |1

我想选择 t.sender OR t.receiver 等于 1 的所有行(我正在为其搜索消息的用户),但要按行的其他值分组(按其他用户分组)。

在此示例中,user1 的结果应包含按 user2、user3 和 user4 值分组的 3 行。

【问题讨论】:

  • 这取决于你想如何分组。如果您想在搜索之前进行分组,请使用 having 子句,否则如果您只想根据发送者或接收者中具有 1 的结果进行分组,则使用 where 子句(可能作为子查询)。
  • grouped by user2, user3, user4 values 是什么意思?你的意思是订购?
  • 我想获取向用户 1 发送消息或被用户 1 发送消息的用户。在此示例中,我只需要 3 行的列名,说它具有值 2、3 和 4 的“目标”

标签: mysql


【解决方案1】:

一种方法是使用union all 获取它们。首先,您需要获取用户发送的消息并将这些结果与同一用户收到的消息合并。

select receiver, count(1), 'Sending' from messages where sender = 1 group by receiver
union all
select sender, count(1), 'Receiving' from messages where receiver = 1 group by sender

【讨论】:

  • 但这会为用户 2 返回两行,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-29
  • 1970-01-01
  • 1970-01-01
  • 2021-01-30
  • 2019-09-15
  • 1970-01-01
  • 2015-05-05
相关资源
最近更新 更多