如何使用表连接和内联视图

时间:2016-01-06 06:53:31

标签: sql oracle jointable

任何人都可以帮助我理解这个SQL查询;我不理解它背后的概念:

SELECT
    t2.*,
    (
        SELECT SUM (salary)
        FROM (
            SELECT
            tb1.*, 
            ROWNUM AS rnk
            FROM ( 
                SELECT *
                FROM employees e
                ORDER BY E.DEPARTMENT_ID, E.EMPLOYEE_ID
            ) tb1
        ) tb2
        WHERE   tb2.DEPARTMENT_ID = t2.DEPARTMENT_ID AND tb2.rnk <= t2.rnk
    ) dept_salary
FROM (
    SELECT   
        t1.*, 
        ROWNUM AS rnk
    FROM (  
        SELECT   
            e.employee_id,
            e.first_name,
            e.department_id,
            e.salary
        FROM employees e
        ORDER BY   E.DEPARTMENT_ID, E.EMPLOYEE_ID
    ) t1
) t2

1 个答案:

答案 0 :(得分:1)

有不同类型的SubQuery。

  1. 标量子查询:完全独立于主查询的查询。

    选择empno,        (从emp中选择count(*))total_emp 来自emp

  2. 这里子查询完全独立于主查询。

    1. 核心子查询:子查询引用主查询。

      选择empno,        (选择deptname         来自dept d         其中e.deptno = d.deptno)deptname 来自emp e

    2. 内联视图:用作SQL

      中的表或视图的子查询

      选择* from(选择empno,deptname       来自emp e,dept d        其中e.deptno = d.deptno) 其中sal> 100

    3. 来自您的查询:

      SELECT
          t2.*,
          (
              SELECT SUM (salary)  -- start Corelated Sub Query
              FROM (
                  SELECT
                  tb1.*, 
                  ROWNUM AS rnk
                  FROM ( 
                      SELECT *  -- start Scalar Sub Query
                      FROM employees e
                      ORDER BY E.DEPARTMENT_ID, E.EMPLOYEE_ID -- end Scalar Sub Query
                  ) tb1 
              ) tb2
              WHERE   tb2.DEPARTMENT_ID = t2.DEPARTMENT_ID AND tb2.rnk <= t2.rnk -- end Corelated Sub Query
          ) dept_salary
      FROM (
          SELECT   -- start inline view
              t1.*, 
              ROWNUM AS rnk
          FROM (  
              SELECT   
                  e.employee_id,
                  e.first_name,
                  e.department_id,
                  e.salary
              FROM employees e
              ORDER BY   E.DEPARTMENT_ID, E.EMPLOYEE_ID
          ) t1
      ) t2  -- end inline view
      

      注意:现在您可以在问题的内联视图中查找子查询和内联视图中的子查询。