gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:23:56 27 4
gpt4 key购买 nike

我有以下源表:

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 重写它。您可以使用 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;

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

关于mysql - 将 SELECT 中的相关子查询重写为 JOIN 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51765722/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com