简体   繁体   中英

Mysql select last row for each group

SELECT  
MAX('time'), c_id, message, state, time 
FROM message 
WHERE receive = 1 
GROUP BY c_id

I have a mysql query, I try to select the last row of each group, but it's not working.

c_id is the group. It select the first row of each group now.

First, you should not escape the column name with single quote since it is not string literal.
Second, you can do subquery which separately get the latest time for every c_id and join it back with the original table to get the other columns.

SELECT  a.*
FROM    message a
        INNER JOIN
        (
            SELECT  c_id, MAX(time) time
            FROM    message
            GROUP   BY c_id
        ) b ON a.c_id = b.c_id AND
                a.time = b.time

or

SELECT  a.*
FROM    message a
WHERE   a.time =
        (
            SELECT  MAX(time) time
            FROM    message b
            WHERE   a.c_id = b.c_id
        ) 
SELECT  
MAX('time'), c_id, message, state, time 
FROM message 
WHERE receive = 1 
GROUP BY c_id
DESC LIMIT 1;

try to use this code

DESC start from the bottom of the table,

LIMIT 1 select just one row (in the example will select the last row)

Thanx to John Woo!

SELECT a.* FROM survey_question_option a INNER JOIN (
   SELECT    subordinate_question, MAX(sort) sort
   FROM      survey_question_option 
   WHERE     question_id=14
   GROUP BY  subordinate_question
) b ON ((a.subordinate_question = b.subordinate_question) OR (a.subordinate_question IS NULL AND b.subordinate_question IS NULL)) AND
a.sort = b.sort AND a.question_id=14;

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