简体   繁体   中英

Get Last row in each group and order whole array by ID(pk) DESC and join with other Table

I want the last row in each and every group(Group By user_id).

Structure of Table is like follows:

Table: user_messages

id(PK) | user_id(FK) | read_admin_status | created_at
 1          5                  0              date
 2          5                  0              date
 3          5                  0              date
 4          5                  1              date
 5          6                  1              date
 6          6                  1              date
 7          7                  0              date
 8          7                  0              date

Table: users

id | username

Now I want username from users tables and I want other details from user_messages.

Now I want data of user_id 5 and want it's last row only. likewise for other groups I want last row of each group and from users table I want username by joining the tables.

Please help me out with this if you can. Thank you.

You might try something like this:

SELECT user_messages.id, users.username
FROM (
    SELECT MAX(id) AS max_id
    FROM user_messages
    GROUP BY user_id
) AS ids
INNER JOIN user_messages ON ids.max_id = user_messages.id
INNER JOIN users ON user_messages.user_id = users.id

This query will choose the largest message ID in each user's group of messages, which is the same as getting the last ID when ordering by ID, and then use the associated user ID to get the username. I only selected the message ID and username, but you could get whatever information you wanted out of those tables.

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