CASE的SUM()WHEN mysql查询忽略限制

时间:2013-06-20 02:22:29

标签: mysql

我总共有4行。球队ID 500有3胜1负。

下面的查询预计会返回最多2个结果,记录为2-0或1-1,具体取决于它是DESC还是ASC。

我一直得到3&的结果1.我不确定在哪里添加限制。

SELECT SUM(CASE WHEN `winner` = 500 THEN 1 ELSE 0 END) AS wins,
       SUM(CASE WHEN `loser` = 500 THEN 1 ELSE 0 END) AS losses
FROM  `schedule`
WHERE  500 IN (`winner`, `loser`)
ORDER BY `date` DESC
LIMIT 2;

1 个答案:

答案 0 :(得分:1)

如果我理解正确,为了实现目标,您必须在子查询中应用LIMIT。 原因是LIMIT在收集结果集的过程中最后应用。

SELECT SUM(CASE WHEN `winner` = 500 THEN 1 ELSE 0 END) AS wins,
       SUM(CASE WHEN `loser`  = 500 THEN 1 ELSE 0 END) AS losses
FROM  
(
  SELECT * 
    FROM schedule 
   WHERE  500 IN (`winner`, `loser`)
   ORDER BY `date` DESC
   LIMIT 2
) q

这是 SQLFiddle 演示。