数据库设计 - 如何在同一个表中拥有主键的外键?

时间:2010-05-17 20:32:03

标签: sql sql-server-2008

我的数据库必须存储我公司的所有可用部门。

有些部门是另一个现有部门的子部门。我决定这样解决这个问题:

Departments
ID Description HeadOfDepartment ParentDepartment

ParentDepartment可以为null,表示它是根部门。如果它有一个父母,我将采取相应的行动,我的问题是如何在Microsoft SQL中对此进行编码?

4 个答案:

答案 0 :(得分:4)

CREATE TABLE Departments 
(
    ID integer primary key, 
    Description varchar(255), 
    HeadOfDepartment varchar(255), 
    ParentDepartment integer references Departments(ID)
);

答案 1 :(得分:1)

允许SQL Server中的外键为NULL或相应表中的有效键。

CREATE TABLE [hierarchytest](
    [ID] [int] NOT NULL,
    [ParentID] [int] NULL,
 CONSTRAINT [PK_hierarchytest] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
))
GO
ALTER TABLE [hierarchytest]  WITH CHECK ADD  CONSTRAINT [FK_hierarchytest_hierarchytest] FOREIGN KEY([ParentID])
REFERENCES [hierarchytest] ([ID])
GO
ALTER TABLE [hierarchytest] CHECK CONSTRAINT [FK_hierarchytest_hierarchytest]

答案 2 :(得分:0)

如果创建外键并强制执行,则不允许在外键字段中放置空值。如果我要实现这样的东西,我会强制执行外键约束,并简单地填充没有父级的部门的外键值和它自己的主键。应该允许这样做。

CREATE TABLE Departments 
(
    Id INT PRIMARY KEY, 
    Description VARCHAR(255), 
    HeadOfDepartment VARCHAR(255), 
    ParentDepartment INT NOT NULL REFERENCES Departments(Id)
);

答案 3 :(得分:-1)

ParentDepartment上创建一个引用表的ID属性的外键。

CREATE TABLE dbo.Departments
    (
    ID int NOT NULL IDENTITY (1, 1),
    Description nvarchar(100) NOT NULL,
    HeadOfDepartment nvarchar(100) NOT NULL,
    ParentDepartment int NULL
    )  ON [PRIMARY]

ALTER TABLE dbo.Departments ADD CONSTRAINT
    PK_Departments PRIMARY KEY CLUSTERED 
    (
    ID
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]

ALTER TABLE dbo.Departments ADD CONSTRAINT
    FK_Departments_Departments FOREIGN KEY
    (
    ParentDepartment
    ) REFERENCES dbo.Departments
    (
    ID
    ) ON UPDATE  NO ACTION 
     ON DELETE  NO ACTION