将表连接到另一个表然后加入自己

时间:2016-03-16 22:43:42

标签: sql oracle join powerbuilder

我正在使用PowerBuilder 12.5连接到Oracle 9.我想通过emp_nbr选择将employee表连接到employee_position表,然后使用该emp_nbr再次加入employee表。

但是,我不想像下面那样使用employee_copy表,因为它很快就会被删除。这是一张图片,展示了我想要做的事情。 :

enter image description here

我不确定是否应该使用嵌套选择,或者只有内部连接才能使用。所以这个SQL代码有效,我成功检索了主管的名字:

 SELECT "EMPLOYEE"."EMP_NBR",   
         "EMPLOYEE"."DEPT_NBR",   
         "EMPLOYEE"."SHOP",   
         "EMPLOYEE"."LAST_NAME",   
         "EMPLOYEE"."FIRST_NAME",   
         "EMPLOYEE"."MIDDLE_INITIAL",   
         "EMPLOYEE"."EMP_CLASS",   
         "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID",   
         "EMPLOYEE_COPY"."LAST_NAME",   
         "EMPLOYEE_COPY"."FIRST_NAME",   
         "EMPLOYEE_COPY"."MIDDLE_INITIAL"  
    FROM "EMPLOYEE",   
         "EMPLOYEE_POSITION",   
         "EMPLOYEE_COPY"  
   WHERE ( "EMPLOYEE"."EMP_NBR" = "EMPLOYEE_POSITION"."EMP_NBR" ) and  
         ( "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID" = "EMPLOYEE_COPY"."EMP_NBR" )

所以我的问题是:如何在不使用employee_copy表的情况下执行此操作?此外,这必须在一个SQL查询中完成。

1 个答案:

答案 0 :(得分:2)

没问题:自我加入可以正常工作:

 SELECT "EMPLOYEE"."EMP_NBR",   
     "EMPLOYEE"."DEPT_NBR",   
     "EMPLOYEE"."SHOP",   
     "EMPLOYEE"."LAST_NAME",   
     "EMPLOYEE"."FIRST_NAME",   
     "EMPLOYEE"."MIDDLE_INITIAL",   
     "EMPLOYEE"."EMP_CLASS",   
     "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID",   
     "EMPLOYEE_MGR"."LAST_NAME" as mgr_last_name,   
     "EMPLOYEE_MGR"."FIRST_NAME" as mgr_first_name,   
     "EMPLOYEE_MGR"."MIDDLE_INITIAL" as mgr_last_name  
FROM "EMPLOYEE",   
     "EMPLOYEE_POSITION",   
     "EMPLOYEE" EMPLOYEE_MGR  
WHERE ( "EMPLOYEE"."EMP_NBR" = "EMPLOYEE_POSITION"."EMP_NBR" ) and  
     ( "EMPLOYEE_POSITION"."EMP_SUPERVISOR_ID" = "EMPLOYEE_MGR"."EMP_NBR" )

只需为EMPLOYEE_MGR的EMPLOYEE表使用别名。