MySQL Query无法按预期工作 - 返回多个响应

时间:2015-02-02 21:29:23

标签: mysql

我有查询:

SELECT * FROM
(
 SELECT
 a.*, 
 (CASE  concat(question_id, type)
 WHEN @curType 
 THEN @curRow := @curRow + 1
 ELSE @curROw := 1 AND @curType := concat(question_id, type) END) + 0 AS rank
 FROM ul_attempt_responses a
 INNER JOIN us_attempts b ON a.attempt_id = b.id
 WHERE b.user_id = 1  and response IS NOT NULL AND trim(response) != ''  and b.authenticated = 1 ORDER BY question_id DESC, type DESC, id DESC) aa
WHERE rank = 1
ORDER BY question_id ASC, type asc;

上面的查询应该在attempt_id上给我最新的回复,并且只给我一个,但是,它给了我2个或更多的回复。

SQLFiddle:http://sqlfiddle.com/#!2/2cd26

我需要一个查询,它将获取用户对所有尝试的最后响应。如果尝试回答了问题,并且下一次尝试没有回答,请获得前一次尝试的回复。

3 个答案:

答案 0 :(得分:0)

试试吧

 SELECT * FROM
 (
  SELECT
 * from  
 (CASE  concat(question_id, type)
  WHEN @curType 
 THEN @curRow := @curRow + 1
 ELSE @curROw := 1 AND @curType := concat(question_id, type) END) + 0 AS      rank
 FROM ul_attempt_responses a
 INNER JOIN us_attempts b ON a.attempt_id = b.id
 WHERE b.user_id = 1  and response IS NOT NULL AND trim(response) != ''  and         b.authenticated = 1 ORDER BY question_id DESC, type DESC, id DESC) aa
WHERE rank = 1
ORDER BY question_id ASC, type asc;)) 

答案 1 :(得分:0)

使用反连接可以更有效地完成此任务:

SELECT ar.*
FROM us_users u
JOIN us_attempts a1
  ON a1.user_id = u.id
LEFT JOIN us_attempts a2
  ON a2.user_id = u.id
  AND a2.id < a1.id
JOIN ul_attempt_responses ar
  ON ar.attempt_id = a1.id
WHERE u.id = 1 AND a2.id IS NULL
ORDER BY question_id, type

如果您想了解有关此技术的更多信息,请查看书籍SQL Antipatterns

答案 2 :(得分:0)

SELECT * FROM ( SELECT sort., (CASE concat(question_id,type) WHEN @curType THEN @curRow := coalesce(@curRow,0) + 1 ELSE @curROw := 1 AND @curType := concat(question_id,type) END) + 1 AS rank from (SELECT a. FROM ul_attempt_responses a LEFT JOIN us_attempts b ON a.attempt_id = b.id WHERE b.user_id = 3 AND response IS NOT NULL AND trim(response) != '' AND b.authenticated = 1 ORDER BY question_id, type, id DESC) sort) final WHERE rank = 2;

这是我正在寻找的答案。