gpt4 book ai didi

sql - 什么时候SELECT后面的子查询不能去掉?

转载 作者:行者123 更新时间:2023-12-04 18:25:25 24 4
gpt4 key购买 nike

相关子查询被认为是 bad habit .我相信任何在 SELECTFROM 之间带有子查询的 SQL 命令(我们称它为 SELECT 子查询)都可以被重写为一个没有任何 SQL 的 SQL 命令。例如这样的查询

select *,
(
select sum(t2.sales)
from your_table t2
where t2.dates
between t1.dates - interval '3' day and
t1.dates and
t2.id = t1.id
) running_sales
from your_table t1

demo

可以改写成下面的

 select dd.id, dd.dates, dd.sales, sum(d.sales) running_sales
from your_table dd
join your_table d on d.dates
between (dd.dates - interval '3' day) and
dd.dates and
dd.id = d.id
group by dd.id, dd.dates, dd.sales

demo

当有多个 SELECT 子查询时可能会出现问题,但是,即使在这种情况下,也可以将它们重写到 FROM 后面的子查询中,然后执行 LEFT JOIN 本着以下精神

select *,
(
select sum(sales)
from dat dd
where dd.dates
between (d.dates - interval '3' day) and d.dates and
dd.id = d.id
) running_sales,
(
select sum(sales)
from dat dd
where dd.id = d.id
) total_sales
from dat d

demo

可以改写成下面的

select d.*,
t_running.running_sales,
t_total.total_sales
from dat d
left join (
select dd.id, dd.dates, sum(d.sales) running_sales
from dat dd
join dat d on d.dates
between (dd.dates - interval '3' day) and
dd.dates and
dd.id = d.id
group by dd.id, dd.dates
) t_running on d.id = t_running.id and d.dates = t_running.dates
left join (
select d.id, sum(d.sales) total_sales
from dat d
group by d.id
) t_total on t_total.id = d.id

demo

能否请您提供一个不可能摆脱 SELECT 子查询的例子?请善待并添加一个工作示例链接(例如 dbfiddlesqlfiddle )以使潜在的讨论更容易,谢谢!

最佳答案

如果问题是多项选择测试(或类似的问题):),则不可能摆脱 EXISTS 子句的子查询。

另一个类似的答案是IN(子查询),用于不同级别的聚合以避免笛卡尔积。

(顺便说一句:相关子查询并不是每次都被认为是坏习惯,它取决于优化、结构等......

WITH 是一种相关子查询的使用……对于复杂的查询非常实用。 )

关于sql - 什么时候SELECT后面的子查询不能去掉?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47084800/

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