1

我总共有 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;
4

1 回答 1

2

如果我对您的理解正确,要实现您的目标,您必须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演示。

于 2013-06-20T02:42:43.463 回答