SQL为组织树选择查询(层次结构)

时间:2015-08-21 20:06:49

标签: sql sql-server tsql hierarchical-data recursive-query

我有一张这样的桌子;

CREATE TABLE [dbo].[TH_ORGANIZATION]
(
    [ID_CORGANIZATION] [decimal](18, 0) IDENTITY(1,1) NOT NULL,
    [ID_CCOMPANY] [nvarchar](10) NOT NULL,
    [CORGANIZATION_NAME_tr] [nvarchar](100) NULL,
    [CORGANIZATION_NAME_en] [nvarchar](100) NULL,
    [CORGANIZATION_MAN_ID_CEMP] [decimal](10, 0) NULL,
    [CORGANIZATION_UPLINK_ID] [decimal](18, 0) NULL,
    [CACTIVE] [bit] NOT NULL CONSTRAINT [DF_TH_ORGANIZATION_CACTIVE]  DEFAULT ((1)),

    CONSTRAINT [PK_TH_ORGANIZATION] 
       PRIMARY KEY CLUSTERED ([ID_CORGANIZATION] ASC)
           WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,  
                 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                 ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO

现在我想写一个SQL查询来获取我的组织树。主列为ID_CORGANIZATION,子组织与CORGANIZATION_UPLINK_ID列相关联,表格相同。

有什么想法吗?

现在最好的解决方案是

 WITH temp as(SELECT * FROM TH_ORGANIZATION WHERE ID_CORGANIZATION = '3'  UNION ALL SELECT ei.* FROM TH_ORGANIZATION ei INNER JOIN temp x ON ei.CORGANIZATION_UPLINK_ID = x.ID_CORGANIZATION ") SELECT * FROM temp

2 个答案:

答案 0 :(得分:0)

SELECT * FROM TH_ORGANIZATION As O,
    TH_ORGANIZATION As Sub
WHERE O.ID_CORGANIZATION 
    = Sub.CORGANIZATION_UPLINK_ID;

您将获得一个包含其子组织的组织列表,递归。当然,您也可以订购列表。

如果您希望所有人都在一列之下,您可以像这样使用外部联接(因此只选择O。*):

SELECT O.* FROM th_organization As O
LEFT OUTER JOIN th_organization As Sub
ON O.id_corganization 
    = Sub.corganization_uplink_id;

示例(我使用缩写),您应该得到这种列表:

id_c uplink_id  name
  1             OrgA
  2             OrgB 
 11      1      subA
 12      1      subB
 21      2      sub2
111     11      subsubA

答案 1 :(得分:0)

我找到的最佳解决方案:

WITH temp as(SELECT * FROM TH_ORGANIZATION WHERE ID_CORGANIZATION = '3'  UNION ALL SELECT ei.* FROM TH_ORGANIZATION ei INNER JOIN temp x ON ei.CORGANIZATION_UPLINK_ID = x.ID_CORGANIZATION ") SELECT * FROM temp

注意:' 3'我刚开始的组织ID