选择最新的答案,还有没有尝试?

时间:2013-10-08 20:11:57

标签: mysql sql

我正在开发测验应用。我的一个表attempts是:

id   qid   answer
--   ---   ------
 1    42   hello
 2     7   magic
 3    42   ni hao
 4    42   ciao
 5     1   foo
 6    42   ohayo

我需要关于第42号问题(qid=42)的最新答案,以及此问题的尝试次数。我试过了:

SELECT answer, count(*) FROM attempts WHERE qid=42 ORDER BY id DESC;

然后我才意识到ORDER BYcount(*)之后执行,所以我的查询给出了第一次尝试的答案,而不是最新的。

我的解决方法是将其拆分为2个查询:

SELECT answer   FROM attempts WHERE qid=42 ORDER BY id DESC LIMIT 1;
SELECT count(*) FROM attempts WHERE qid=42;

我想知道这是否可以合并为1个查询?

1 个答案:

答案 0 :(得分:1)

这应该可以得到每个qid的1个结果w /尝试次数以及与第一次尝试相关的答案。

SELECT A.qid, answer as FirstAnswer, B.Attempts 
FROM attempts A 
INNER JOIN (SELECT DISTINCT
    qid,
    COUNT(*) over(Partition by qid) as NumberAttempts,
    MIN(id) over(partition by qid) as First_AnswerID
    from attempts) B ON A.id = B.First_AnswerID

... OR

SELECT A.qid, A.answer as FirstAnswer, B.NumAtmps, C.FirstID FROM attempts A
INNER JOIN (SELECT qid, count(*) as NumAtmps FROM attempts group by qid) B ON A.qid = B.qid 
INNER JOIN (SELECT qid, min(id) as FirstID FROM attempts group by qid) C ON A.qid = C.qid AND A.id = C.FirstID