表Races
包含Time
,Racetrack
和Racer
列。
表Racetracks
包含Name
和Length
列。
以下查询执行复杂的选择以查找Racetracks
表(下部)的单行,然后计算此赛道的某些属性(上部)。其中一个属性是这里的平均比赛时间。
SELECT
(select avg(Time) from Races where Racetrack = t.Name) as AverageTime
/* more lines like the one above to calculate information about this track */
FROM (select * from Racetracks
/* complicated where clauses to select a particular racetrack */
limit 1
) as t;
我想稍微修改一下查询。而不是所有比赛的平均比赛时间,只应平均每个赛车的最佳时间。这就是我试过的:
SELECT
(select avg(BestTime) from (select min(Time) as BestTime from Races where Racetrack = t.Name group by Racer) as b) as AverageTime
/* more lines like the one above to calculate information about this track */
FROM (select * from Racetracks
/* complicated where clauses to select a particular racetrack */
limit 1
) as t;
尽管MySQL引发了以下错误:
ERROR 1054 (42S22): Unknown column 't.Name' in 'where clause'
这似乎与https://dba.stackexchange.com/questions/126339/subquery-cant-find-column-from-superquerys-join相关,但我无法弄清楚如何以有效的方式重写我的查询。
答案 0 :(得分:0)
没有简单的方法可以做到这一点。您可以预先计算所有赛道的值:
SELECT (select avg(BestTime)
from (select RaceTrack, Racer, min(Time) as BestTime
from Races
group by RaceTrack, Racer
) r
where r.Racetrack = t.Name
) as AverageTime
/* more lines like the one above to calculate information about this track */
FROM (select * from Racetracks
/* complicated where clauses to select a particular racetrack */
limit 1
) as t;
对于一个赛道,如果逻辑是子查询或from
子句,则无关紧要。如果您同时进行多个赛道,我建议您在from
子句中进行预先总结。