簡體   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