SQL查询和优化(九)

用LEFT JOIN 优化标量子查询
多次访问同一个表时,尽量不用标量子查询

SELECT s.sid,
        s.sname,
        s.shot,
        s.stype,
        (SELECT a.aid FROM a WHERE a.aid =s.aids) aid,
        (SELECT a.aname FROM a WHERE a.aid =s.aids) aname,
        (SELECT a.atime FROM a WHERE a.aid =s.aids) aatime
    FROM s;

可以看到,在标量子查询中对a表访问了三次,而且关联条件一样,直接改为LEFT JOIN的方式

SELECT s.sid,s.sname,s.type,s.shot,a.aid,a.anme,a.aatime
FROM s
LEFT JOIN a ON(a.aid=s.aids);

再看下面的例子,当标量子查询中有聚合时的改写

SELECT d.department_id,
        d.department_name,
        d.location_id,
        nvl((SELECT SUM(e.salary)FROM hr.employees e
        WHERE e.department_id = d.department_id),0) AS sum_sal
FROM hr.departments d;

改写时,要先汇总,后关联

SELECT d.department_id,
        d.department_name,
        d.location_id,
        nvl (e.sum_sal,0) AS sum_sal
    FROM hr.departments d 
    LEFT JOIN (SELECT e.department_id,SUM(e.salary)AS sum_sal 
                FROM hr.employees e
                GROUP BY e.department_id) e
    ON (e.department_id = d.department_id);

选自《Oracle 查询优化改写技巧与案例》 有教无类 落落 著

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值