温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

标量子查询

发布时间:2020-06-26 22:35:36 来源:网络 阅读:452 作者:llc018198 栏目:关系型数据库

--标量子查询
select e.empno, e.ename, e.sal, e.deptno,
       (select d.dname from dept d where e.deptno = d.deptno)as dname
  from emp e
--插入一条数据
insert into emp(empno,deptno) values(9999,null)--返回结果15条记录
--改成left join(hash outer)
select e.empno, e.ename, e.sal, e.deptno,d.dname
  from emp e
  left join dept d
    on (e.deptno = d.deptno)
--NL outer
select /*+ use_nl(e,d) */e.empno, e.ename, e.sal, e.deptno,d.dname
  from emp e
  left join dept d
    on (e.deptno = d.deptno)
/*Note:修改后plan一般有outer字样,如果没有,注意是否改错。*/

--用left join 优化标量子查询之聚合改写
select dp.department_id, dp.department_name, dp.location_id,
       nvl((select sum(em.salary)
              from hr.employees em
             where em.department_id = dp.department_id),
            0) as sum_dept_salary
  from hr.departments dp

--错误写法
select dp.department_id, dp.department_name, dp.location_id,
       nvl(sum(em.salary), 0) as sum_sal
  from hr.departments dp
  left join hr.employees em
    on dp.department_id = em.department_id
    
--原标量子查询改写为:

select em.department_id, sum(em.salary) as sum_sal
  from hr.employees em
 group by em.department_id
 
 --左联改写后的内联视图
  select dp.department_id, dp.department_name, dp.location_id,
         nvl(sum(e.sum_sal), 0) as sum_sal
    from hr.departments dp
    left join (select e.department_id, sum(e.salary) as sum_sal
                 from hr.employees e
                group by e.department_id) e
      on (dp.department_id = e.department_id)
   group by dp.department_id, dp.department_name, dp.location_id
--
create table dept2 as select * from scott.dept;
insert into dept2  select * from scott.dept where deptno=10

select t1.job, t1.deptno,
       (select distinct dname from dept2 b where b.deptno = t1.deptno) as dname
  from scott.emp t1
 order by 1, 2, 3
--以下改写结果变了
select distinct t1.job, b.deptno, b.dname
  from scott.emp t1
  left join dept2 b
    on t1.deptno = b.deptno
--正确改写
select t1.job, t1.deptno, f.dname
  from scott.emp t1
  left join (select b.deptno, b.dname
               from dept2 b
              group by b.deptno, b.dname) f
    on (f.deptno = t1.deptno)

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI