简体   繁体   中英

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

I am not very experienced in MySQL.

I have a table that has: unique_id (auto_increment), user_id, other_user_id, timestamp and some other fields.

Let's assume I have some values:

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

What I want to do is the following: For a single user (let's assume the user_id = 10 above) I want to find all the rows that he is in with all other users (eg 11, 12) and get only the last ones (time-wise) for each.

So for the data above the result should be rows 4 and 5. Row 4 because it is the last one found between 10 and 11. Row 5 because it is the last one (and only one in this example) found between 10 and 12. Same for any other rows 10 would be in with other users.

What would be the query for that?

You can use a query like the following:

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

The derived table is used to extract the unique_id value associated with the latest record per user_id, other_user_id pair. Since this is also, presumably, the PK of the table we can use this value in order to get the related record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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