使用内部联接分组多个列

时间:2017-06-12 19:29:41

标签: mysql sql

我有以下数据库。

msg
....
 - uid (pk)
 - sender
 - msg

relation
---------
 - uid (fk)
 - reciever

邮件可以发送给多个收件人,我希望收到所有收件人和发件人的唯一列表。问题是发件人也可能是收件人,所以我得到重复。

一个例子是:

SELECT  msg.sender,relation.reciever,msg.msg,msg.uid from msg inner join relation on msg.uid = relation.uid group by msg.sender;


+-------------+-------------+-------+-----+
| sender      | reciever    | msg   | uid |
+-------------+-------------+-------+-----+
| 123         | 321         | Test1 | 1   |
| 321         | 123         | Test2 | 2   |
+-------------+-------------+-------+-----+

现在的问题是,存在重复数据。我想要其中一个,而不是两个领域中发送者或接收者都是唯一的。为了实现这一点,我在组中添加了msg.reciever,如下所示:

SELECT  msg.sender,relation.number,msg.msg,msg.uid from msg inner join
 relation on msg.uid = relation.uid group by msg.sender, relations.reciever;

但结果是一样的。我如何完成跨两列产生独特结果的任务?

澄清最终结果应为:

+-------------+-------------+-------+-----+
| sender      | reciever    | msg   | uid |
+-------------+-------------+-------+-----+
| 123         | 321         | Test1 | 1   |
+-------------+-------------+-------+-----+

+-------------+-------------+-------+-----+
| sender      | reciever    | msg   | uid |
+-------------+-------------+-------+-----+
| 321         | 123         | Test2 | 2   |
+-------------+-------------+-------+-----+

1 个答案:

答案 0 :(得分:0)

使用联合创建一个单独的列,在该列上应用分组依据。

类似这样的东西:

select * from 
(
      SELECT  msg.sender as user, msg.msg,msg.uid from msg 
      inner join relation on msg.uid = relation.uid
   union
      SELECT  relation.reciever as user, msg.msg,msg.uid from msg 
      inner join relation on msg.uid = relation.uid
) Temp
group by user