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

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

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

4

3 回答 3

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
        ) 
于 2013-07-24T09:42:16.380 回答
1
SELECT  
MAX('time'), c_id, message, state, time 
FROM message 
WHERE receive = 1 
GROUP BY c_id
DESC LIMIT 1;

尝试使用此代码

DESC从表格底部开始,

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

于 2021-05-27T06:55:12.853 回答
0

感谢吴宇森!

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;
于 2014-11-25T11:23:47.817 回答