Mysql select last row for each group

偶尔善良 提交于 2019-12-29 06:36:30

问题


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.


回答1:


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
        ) 



回答2:


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;


来源:https://stackoverflow.com/questions/17830355/mysql-select-last-row-for-each-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!