我想删除mysql数据库中的任何不对称列值

时间:2016-08-21 19:01:19

标签: mysql

SELECT * 
from message m , message_viewer v 
where m.id = v.message_id 
group by m.author_id , v.viewer_id, m._date

id | author_id | viewer_id | read
1  |    103    |    102    | 0
2  |    102    |    103    | 1
3  |    101    |    103    | 0
4  |    103    |    101    | 0

我希望结果是

id | author_id | viewer_id | read
1  |    103    |    102    | 0
4  |    103    |    101    | 0

1 个答案:

答案 0 :(得分:0)

由于您希望通过作者和观看者的独特组合来汇总结果,因此使用leastgreatest选择了一个选项:

select max(m.id) as id,
    least(m.author_id, mv.viewer_id) as author_id,
    greatest(m.author_id, mv.viewer_id) as viewer_id
from message m 
  join message_viewer mv on m.id = mv.message_id
group by least(m.author_id, mv.viewer_id),
    greatest(m.author_id, mv.viewer_id)

这会应用max聚合来返回消息ID - 如果没有它,您只会收到返回的任意结果。您的问题也不清楚read列的来源。