简体   繁体   English

获取具有两列组合的唯一行

[英]Get unique rows with combination of two columns

Having this private chat table 有这个私人聊天表 在此输入图像描述

On my message page I want to show latest conversations list. 在我的消息页面上,我想显示最新的对话列表。 List will be like if am sending message from pc to pc2 and pc2 sending back to pc then it should show only one row. 列表将是如果从pc发送消息到pc2pc2发送回PC然后它应该只显示一行。

I tried this query 我试过这个查询

SELECT id, col2, col3, col4 FROM yourtable GROUP BY col2, col3; SELECT id,col2,col3,col4 FROM yourtable GROUP BY col2,col3;

Selecting distinct 2 columns combination in mysql 在mysql中选择不同的2列组合

But it's resulting in 但它导致了

在此输入图像描述

Update: 更新:

I tried this query 我试过这个查询

SELECT * FROM tbl_primessages Where frmid = 3466 OR toid = 3466 GROUP BY frmid, toid ORDER BY tbl_primessages . SELECT * FROM tbl_primessages其中frmid = 3466或toid = 3466 GROUP BY frmid,toid ORDER BY tbl_primessages timestemp DESC timestemp DESC

Update 2 It should be with the latest time from two 更新2它应该是最新的两个时间

The query below used a least/greatest trick to group together messages involving the same pair of users. 下面的查询使用最小/最大的技巧将涉及同一对用户的消息组合在一起。 Then, we can retain the latest conversation per pair of people. 然后,我们可以保留每对人的最新对话。

SELECT t1.*
FROM tbl_primessages t1
INNER JOIN
(
    SELECT
        LEAST(frmid, toid) AS frmid,
        GREATEST(frmid, toid) AS toid,
        MAX(timestamp) AS latest_ts
    FROM tbl_primessages
    GROUP BY LEAST(frmid, toid), GREATEST(frmid, toid)
) t2
    ON LEAST(t1.frmid, t1.toid)    = t2.frmid AND
       GREATEST(t1.frmid, t1.toid) = t2.toid  AND
       t1.timestamp = t2.latest_ts

Demo here: 在这里演示:

Rextester Rextester

In the SELECT use only fields from the GROUP BY plus some aggregate functions (COUNT, AVG, MIN, MAX, etc). 在SELECT中仅使用GROUP BY中的字段加上一些聚合函数(COUNT,AVG,MIN,MAX等)。

SELECT frmid, toid
FROM tbl_primessages
Where frmid = 3466 OR toid = 3466
GROUP BY frmid, toid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM