SQL - MAX函数返回错误数据

时间:2013-12-13 11:57:44

标签: mysql sql select group-by groupwise-maximum

我正在尝试使用max seq_no记录的每个问题,但它返回了错误的数据。

这是查询:

SELECT id, attempt, seq_number, question
FROM question_states
WHERE attempt = 374
AND seq_number IN ( SELECT MAX(seq_number) FROM question_states WHERE attempt = 374 GROUP BY question)
GROUP BY question, id

我有一个表名作为问题,结构如下: -

id--seq_number--attempt--question
1 --0     --374  -- 130
2 --0     --374  -- 130
3 --1     --374  -- 130
4 --2     --374  -- 130
5 --1     --374  -- 131

为什么此查询会针对问题130返回2条记录?如果我删除GROUP BY id然后返回错误的数据。

2 个答案:

答案 0 :(得分:2)

试试这个:

SELECT id, attempt, seq_number, question
FROM question_states qs 
INNER JOIN (SELECT question, MAX(seq_number) seq_number 
            FROM question_states WHERE attempt = 374 GROUP BY question
           ) AS A ON qs.question = A.question AND qs.seq_number = A.seq_number 
WHERE attempt = 374

SELECT id, attempt, seq_number, question
FROM (SELECT id, attempt, seq_number, question
      FROM question_states WHERE attempt = 374
      ORDER BY question, seq_number DESC
     ) AS A 
GROUP BY question

答案 1 :(得分:0)

在子查询中,由于您使用了group by,它将返回两个值“2”和“1”。 并且在主查询中,因为您使用了'IN'语句,它将返回包含字段seq_number和attempt = 374的所有数据

尝试

选择max(seq_number),id,尝试,来自question_states组的问题by seq_number ORDER by seq_number DESC limit 1