左外部联接与带有内部联接的子查询

时间:2018-12-26 12:31:45

标签: sql-server join criteria hibernate-criteria criteria-api

我有一个SQL查询,我想使用Criteria API进行转换。

我想将EMPLOYEE的左外部联接与子查询的结果集组合在一起,该子查询通过内部联接查询不同的表。

SELECT 
    E1.EMPNO, E1.LASTNAME, E1.WORKDEPT, D1.DEPTNAME ,O1.OrgId
FROM 
    E1.EMPLOYEE 
LEFT OUTER JOIN
    (SELECT * 
     FROM Organization O1 
     INNER JOIN Departmental D2 ON D2.OrgId = O1.OrgId
     INNER JOIN Departmental D3 ON D3.OrgId = E2.OrgId) D1 ON D1.DeptNo = E1.WORKDEPT

2 个答案:

答案 0 :(得分:1)

您可以编写查询,如下所示。在这里,您为同一表D1的连接多次赋予了相同的别名Departmental

SELECT 
    E1.EMPNO, E1.LASTNAME, E1.WORKDEPT, D1.DEPTNAME ,O1.OrgId
FROM 
    EMPLOYEE E1
LEFT OUTER JOIN
    (SELECT * 
     FROM Organization O1 
     INNER JOIN Departmental D2 ON D2.OrgId = O1.OrgId
     INNER JOIN Departmental D3 ON D3.OrgId = E2.OrgId
     -- add where condition if required
    ) D1 
     ON D1.DeptNo = E1.WORKDEPT
   -- add where condition if required

答案 1 :(得分:1)

请检查以下SQL查询

SELECT 
    E1.EMPNO, E1.LASTNAME, E1.WORKDEPT, D1.DEPTNAME, 
    D1.O1OrgId
FROM E1.EMPLOYEE 
LEFT OUTER JOIN ( 
    select
        O1.OrgId as O1OrgId,
        D1.DeptNo as D1DeptNo
    from Organization O1 
    inner join Departmental D1 
        on D1.OrgId=O1.OrgId
) D1 
    on D1.D1DeptNo = E1.WORKDEPT

不能从外部SQL SELECT语句引用子选择中使用的表别名

表别名也有作用域

您只能从外部查询的子选择语句中引用SELECT列表中的字段