SELECT
MAX('time'), c_id, message, state, time
FROM message
WHERE receive = 1
GROUP BY c_id
我有一个 mysql 查询,我尝试选择每个组的最后一行,但它不起作用。
c_id 是组。它现在选择每个组的第一行。
SELECT
MAX('time'), c_id, message, state, time
FROM message
WHERE receive = 1
GROUP BY c_id
我有一个 mysql 查询,我尝试选择每个组的最后一行,但它不起作用。
c_id 是组。它现在选择每个组的第一行。
首先,您不应该使用单引号转义列名,因为它不是字符串文字。
其次,您可以执行子查询,分别获取每个的最新时间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
)
SELECT
MAX('time'), c_id, message, state, time
FROM message
WHERE receive = 1
GROUP BY c_id
DESC LIMIT 1;
尝试使用此代码
DESC
从表格底部开始,
LIMIT 1
只选择一行(在示例中将选择最后一行)
感谢吴宇森!
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;