重写select into join语句中的相关子查询

pxy2qtax  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(353)

我有以下源表:

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 陈述并取得相同的结果?

qncylg1j

qncylg1j1#

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

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

你不能仅仅用 join . 你可以用 join 以及 group 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;

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

相关问题