MxL*_*evs 28 sql plsql code-cleanup
我正在编写一些带有多个子查询和大量连接的SQL查询,包括子查询内部和子查询中的结果表.
我们没有使用视图,所以这是不可能的.
在写完之后我正在看着它并且挠头想知道它甚至在做什么,因为我无法遵循它.
你用什么样的格式来试图清理这么乱?也许缩进?
Ale*_*aho 19
对于大型查询,我倾向于使用命名结果集WITH.这允许事先定义结果集,并使主查询更简单.命名结果集可能有助于使查询计划更有效,例如postgres将结果集存储在临时表中.
例:
WITH
cubed_data AS (
SELECT
dimension1_id,
dimension2_id,
dimension3_id,
measure_id,
SUM(value) value
FROM
source_data
GROUP BY
CUBE(dimension1, dimension2, dimension3),
measure
),
dimension1_label AS(
SELECT
dimension1_id,
dimension1_label
FROM
labels
WHERE
object = 'dimension1'
), ...
SELECT
*
FROM
cubed_data
JOIN dimension1_label USING (dimension1_id)
JOIN dimension2_label USING (dimension2_id)
JOIN dimension3_label USING (dimension3_id)
JOIN measure_label USING (measure_id)
Run Code Online (Sandbox Code Playgroud)
这个例子有点做作,但我希望它显示与内联子查询相比清晰度的提高.在为OLAP使用准备数据时,命名结果集对我很有帮助.如果您要/想要创建递归查询,则必须使用命名结果集.
WITH 至少适用于Postgres,Oracle和SQL Server的当前版本
Dat*_*onk 10
男孩这是一个有问题的人.:)有很多方法可以做到这一点,因为这个网站上有聪明的人.也就是说,这是我在构建复杂的sql语句时保持自己的理智:
select
c.customer_id
,c.customer_name
,o.order_id
,o.order_date
,o.amount_taxable
,od.order_detail_id
,p.product_name
,pt.product_type_name
from
customer c
inner join
order o
on c.customer_id = o.customer_id
inner join
order_detail od
on o.order_id = od.order_id
inner join
product p
on od.product_id = p.product_id
inner join
product_type pt
on p.product_type_id = pt.product_type_id
where
o.order_date between '1/1/2011' and '1/5/2011'
and
(
pt.product_type_name = 'toys'
or
pt.product_type_name like '%kids%'
)
order by
o.order_date
,pt.product_type_name
,p.product_name
Run Code Online (Sandbox Code Playgroud)
如果您感兴趣,我可以发布/发送插入,更新和删除以及相关子查询和复杂连接谓词的布局.
这回答了你的问题了吗?