繁体   English   中英

对于特定的user_id,在MySQL中获取该用户与所有其他用户一起的最新行(按时间)

[英]For a specific user_id get the latest rows (time-wise) that this user is in with all other users, in MySQL

我对MySQL不是很有经验。

我有一个表:unique_id(auto_increment),user_id,other_user_id,timestamp和其他一些字段。

我们假设我有一些值:

unique_id user_id other_user_id     timestamp
  1          10       11          yyyy-mm-dd hh:mm:ss
  2          11       10          yyyy-mm-dd hh:mm:ss
  3          11       12          yyyy-mm-dd hh:mm:ss
  4          11       10          yyyy-mm-dd hh:mm:ss
  5          10       12          yyyy-mm-dd hh:mm:ss

我想要做的是以下内容:对于单个用户(让我们假设user_id = 10以上)我想找到他与所有其他用户(例如11,12)的所有行,并且只获取最后一行(每个时间)。

因此对于上面的数据,结果应该是第4行和第5行。第4行因为它是在10和11之间找到的最后一行。第5行因为它是10到12之间的最后一个(在本例中只有一个)。对于任何其他行,10将与其他用户相同。

对此有什么疑问?

您可以使用如下查询:

SELECT t1.*
FROM mytable
JOIN (
   SELECT LEAST(user_id, other_user_id) AS user1,
          GREATEST(user_id, other_user_id) AS user2,
          MAX(unique_id) AS max_id
   FROM mytable
   GROUP BY LEAST(user_id, other_user_id),
            GREATEST(user_id, other_user_id)
) AS t2 ON t1.unique_id = t2.max_id

派生表用于提取与每个user_id, other_user_id对的最新记录关联的unique_id值。 由于这也可能是表格的PK,我们可以使用这个值来获得相关记录。

暂无
暂无

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

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