问题
SELECT series_id, team, SUM(Win) As Won, SUM(Loss) as Lost
FROM
( SELECT *,radiant_name as team,
CASE WHEN radiant_win = 1 THEN 1 ELSE 0 END as Win,
CASE WHEN radiant_win = 1 THEN 0 ELSE 1 END as Loss
FROM matches
UNION ALL
SELECT *,dire_name as team,
CASE WHEN radiant_win = 0 THEN 1 ELSE 0 END as Win,
CASE WHEN radiant_win = 0 THEN 0 ELSE 1 END as Loss
FROM matches
) as temp
WHERE series_id = 8313
GROUP By team
ORDER By Won, Lost DESC
答案 0 :(得分:1)
优化这一点的领域包括:
不要选择*。只选择您需要的字段。换句话说,这个:
SELECT *,radiant_name as team
可以是这样的:
SELECT series_id,radiant_name as team
接下来,派生表没有过滤,所以它查询整个表。这样:
WHERE series_id = 8313
应该进入你的子查询 - 两次。
最后,如果您只对一个series_id感兴趣,那么选择它是没有意义的。您的查询可能类似于:
SELECT team, SUM(Win) As Won, SUM(Loss) as Lost
FROM
( SELECT radiant_name as team,
CASE WHEN radiant_win = 1 THEN 1 ELSE 0 END as Win,
CASE WHEN radiant_win = 1 THEN 0 ELSE 1 END as Loss
FROM matches
WHERE series_id = 8313
UNION ALL
SELECT dire_name as team,
CASE WHEN radiant_win = 0 THEN 1 ELSE 0 END as Win,
CASE WHEN radiant_win = 0 THEN 0 ELSE 1 END as Loss
FROM matches
WHERE series_id = 8313
) as temp
GROUP By team
ORDER By Won, Lost DESC
答案 1 :(得分:1)
我认为,这些案例陈述是查询的丑陋部分。我会通过减去总计数的胜利数来计算胜负,反之亦然:
select series_id, team, sum(won), sum(lost)
from
(
select series_id, radiant_name as team, sum(radiant_win) as won, count(*)-sum(radiant_win) as lost
from matches
group by series_id, radiant_name
union all
select series_id, dire_name as team, count(*)-sum(radiant_win) as won, sum(radiant_win) as lost
from matches
group by series_id, dire_name
)
where series_id = 8313
group by series_id, team
order by won, lost desc