0

我有一个极其难看的复杂查询,它根据一系列分组返回比赛结果。

我有一个包含注册信息(名称等)的表,以及一个包含完成时间的表。我需要为每个种族、班级和部门(它们是彼此的子组)找到一个位置。

我现在的工作是这样的:

Select reg.name, r.fin_time
  ( select count(*)+1 from 
    ( Select temp_reg.id as regid, temp_reg.race_id as in_race, temp_res.division as in_div, 
         COALESCE(temp_res.fin_time, 9999999999) as finish_time 
      FROM results as temp_res Inner JOIN registration as temp_reg on temp_res.registration_id = temp_reg.id 
      WHERE COALESCE(temp_res.fin_time) > 0 
        AND temp_res.status ='Finished') as ahead_div 
    WHERE ahead_div.regid <> reg.registration_id 
      AND ahead_div.in_race = reg.race_id 
      AND ahead_div.in_div = r.division 
      AND ahead_div.finish_time < COALESCE(r.fin_time, 9999999999) ), '-') as fin_place_div,
... same for class and race...
FROM results as r inner join registration as reg on r.registration_id = reg.id 
WHERE r.status = 'Finished';

所以我把所有完赛的选手都收集起来,统计他们在同一个比赛同一个分区的位置,他们的完赛时间是<这个记录的完赛时间。

我现在有一种情况,我需要将计算出的比赛完成地点显示为班级完成地点。所以我需要在 if 语句中复制比赛位置子查询(丑陋和慢),或者将子查询移动到 where子句,所以我可以多次使用它们。

我如何将这个查询从选择中的“count() from subquery where”单值子查询重新格式化为连接?

有什么我可以重用内部子查询的吗?如果将课程添加到其中,我可以从它计算每个地方的计数。

干杯,

4

1 回答 1

0

I know this won't help your code look any cleaner, but performance wise if you simply re-use the same subquery it will likely be cached so there shouldn't be a performance hit (generally as long as it doesn't use session variables or is a correlated subquery).

See what EXPLAIN EXTENDED says and provided it doesn't come back with DEPENDENT SUBQUERY or UNREACHABLE SUBQUERY there shouldn't be a performance hit.

SELECT
   *
FROM
   (SELECT a FROM a) b INNER JOIN
   (SELECT a FROM a) c ON b.a = c.a

The query optimizer should cache the subquery so that it is not actually retrieved twice.

于 2013-06-02T02:51:08.347 回答