将SELECT中的相关子查询重写为JOIN语句

时间:2018-08-09 11:24:51

标签: mysql sql subquery correlated-subquery

我有以下源表:

CREATE TABLE test
    (`step` varchar(1), `cost_time` int, `rank_no` int)
;

INSERT INTO test
    (`step`, `cost_time`, `rank_no`)
VALUES
    ('a', 10, 1),
    ('b', 20, 2),
    ('c', 30, 3)
;

并像这样查询:

select 
  main.step,
  main.cost_time,
  main.rank_no,
  (select sum(sub.cost_time)
  from test sub
  where sub.rank_no <= main.rank_no)  as total_time
from
  test main

预期结果:

| step | cost_time | rank_no | total_time |
|------|-----------|---------|------------|
|    a |        10 |       1 |         10 |
|    b |        20 |       2 |         30 |
|    c |        30 |       3 |         60 |

是否可以使用join语句重写此sql并获得相同的结果?

1 个答案:

答案 0 :(得分:2)

编写此查询的最佳方法是使用累计和:

select main.step, main.cost_time, main.rank_no,
       sum(cost_time) over (order by rank_no) as total_time
from test main;

您不能仅使用join来重写它。您可以使用joingroup by重写它:

select main.step, main.cost_time, main.rank_no,
       sum(sub.cost_time) as total_time
from test main join
     test sub
     on sub.rank_no <= main.rank_no
group by main.step, main.cost_time, main.rank_no;

但是,我认为相关子查询是一个更好的解决方案。