简体   繁体   中英

I want to get last row in mysql using group by

SELECT * FROM msg_messages m 
JOIN msg_status s on m.messageId = s.messageId 
JOIN msg_threads t ON t.threadId = m.threadId 
JOIN users u ON u.userId = s.userId 
WHERE t.threadId = 1 
GROUP BY u.userId ORDER BY `m`.`date` DESC 

this is the query which give me always first index of every record. but i want get latest index in each group.. i tried many ways but result is nothing. user: 这是没有摸索的

这是通过摸索

这是我在分组后想要的

这就是给我的

TRY THIS CODE

SELECT * FROM msg_messages m 
JOIN msg_status s on m.messageId = s.messageId 
JOIN msg_threads t ON t.threadId = m.threadId 
JOIN users u ON u.userId = s.userId 
WHERE t.threadId = 1 
GROUP BY u.userId ORDER BY `m`.`date` DESC LIMIT 0,1

how about this:

SELECT * FROM msg_messages m 
JOIN msg_status s on m.messageId = s.messageId 
JOIN msg_threads t ON t.threadId = m.threadId 
JOIN users u ON u.userId = s.userId 
GROUP BY u.userId 
having max (`m`.`date`)
ORDER BY `m`.`date` DESC 

I revised my query from

having max (`t`.`threadId`)

to

having max (`m`.`date`)

you can use LIMIT 1 after DESC then you will get last record. example: DESC LIMIT 1;

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