Mysql为每个组选择最后一行

时间:2013-07-24 09:40:23

标签: mysql greatest-n-per-group

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

我有一个mysql查询,我尝试选择每个组的最后一行,但它不起作用。

c_id是该组。它现在选择每个组的第一行。

3 个答案:

答案 0 :(得分:11)

首先,您不应该使用单引号转义列名,因为它不是字符串文字。
其次,您可以执行子查询,该子查询分别获取每个c_id的最新时间,并将其与原始表联接以获取其他列。

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

SELECT  a.*
FROM    message a
WHERE   a.time =
        (
            SELECT  MAX(time) time
            FROM    message b
            WHERE   a.c_id = b.c_id
        ) 

答案 1 :(得分:1)

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

尝试使用此代码

DESC 从表格底部开始,

LIMIT 1 只选择一行(在示例中将选择最后一行)

答案 2 :(得分:0)

Thanx给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;