SQL解析来自同一表的外键

时间:2019-02-25 16:39:38

标签: sql join select key

我希望您能为初学者提供一些帮助。我得到一个引用几个表的查询。我要引用的两个表拥有一个外键,这将是联合表中的不同记录。

此处的示例为orgunit.shortname。该字段将被调用两次,但关系不同。

我确定有一种方法可以不使用临时表来完成此操作,但是我多次尝试都失败了。

任何帮助将不胜感激。

最佳 丹尼斯

当前查询如下。

select 
    orgunit.shortname       AS OnsiteDept, 
    department.shortname    AS DeptName, 
    OrgUnitParent.orgunitid AS ParentID,
    Orgunit.xrefcode        AS OrgXref,
    Orgunit.departmentid    AS DeptID,  
    Orgunit.shortname       AS Parentshotname,
    Orgunit.orglevelid      AS OrgLevel

        from orgunit
        left join   department
        on orgunit.departmentid = department.departmentid

        left join   OrgUnitParent
        on orgunit.orgunitid = OrgUnitParent.orgunitid
        AND OrgUnitParent.orgunitid = orgunit.orgunitid

            where orgunit.shortname

1 个答案:

答案 0 :(得分:0)

select ou.shortname       AS OnsiteDept, 
       d.shortname    AS DeptName, 
       oup.orgunitid AS ParentID,
       ou.xrefcode        AS OrgXref,
       ou.departmentid    AS DeptID,  
       oup.shortname       AS Parentshotname,
       ou.orglevelid      AS OrgLevel    
from orgunit ou left join
     department d
     on ou.departmentid = d.departmentid left join
     OrgUnitParent
     on oup.orgunitid = ou.parent_orgunitid left join
     orgunit oupp
     on oupp.orgunitid = oup.orgunitid
where ou.shortname;

组织单位与其父单位之间的联接并不明显。也许有某种父母身份。