1

我正在尝试解决每个具有 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

为什么此查询针对 question 返回 2 条记录130?如果我删除GROUP BY idthen 返回错误的数据。

4

2 回答 2

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
于 2013-12-13T12:05:13.580 回答
0

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

尝试

select max(seq_number), id, attempt, question from question_states group by seq_number ORDER by seq_number DESC limit 1

于 2013-12-13T12:31:30.923 回答