mysql - 子子查询无法访问在外部范围内定义的表

标签 mysql sql subquery

Races 包含列 TimeRacetrackRacer

Racetracks 包含列 NameLength

以下查询执行复杂的选择以查找 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但我不知道如何以有效的方式重写我的查询。

最佳答案

没有简单的方法可以做到这一点。您可以预先计算所有赛道的值:

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 子句中进行预先汇总。

关于mysql - 子子查询无法访问在外部范围内定义的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44640149/

相关文章:

SQL INNER JOINing 2 个子查询

mysql - 将日期时间模式 'y-M-d H:m:s' 选择条件与日期类型进行比较

mysql - 分组 sum 、 count 和 max 以按多列分组

mysql - 按一个字段分组并统计匹配字段

mysql - 选择查询与 cte 的联合

mysql - 将子查询转换为联接以用作 View

php - 10天后删除处理订单

php - 如何在参数为空时获取所有值

MySQL - 添加标志列以识别首次付款

Mysql 子查询的执行