将 SELECT 中的相关子查询重写为 JOIN 语句
Rewrite correlated subquery in SELECT into JOIN statement
我有以下来源 table:
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 并获得相同的结果?
编写此查询的最佳方式是使用累计和:
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;
不过,我认为相关子查询是一个更好的解决方案。
我有以下来源 table:
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 并获得相同的结果?
编写此查询的最佳方式是使用累计和:
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;
不过,我认为相关子查询是一个更好的解决方案。