是否可以向外键添加逻辑约束?

时间:2009-06-24 03:05:09

标签: sql tsql foreign-keys constraints

我有两个表,我添加了一个外键约束。 Kewl - 效果很好。现在,是否有可能进一步限制父表中某些数据的关系?

基本上,我在父表中有动物,而子表希望只包含父数据为......嗯哺乳动物的数据。

例如

Animals
^^^^^^^
AnimalId INT PK NOT NULL IDENTITY
AnimalType TINYINT NOT NULL -- 1: Mammal, 2:Reptile, etc..
Name

Mammals
^^^^^^^
AnimalId INT PK FK NOT NULL
NumberOfMammaryGlads TINYINT NOT NULL

所以,我希望确保AnimalId只能是Animals.AnimalType = 1

类型

这可能吗?

我不想让某人尝试在儿童表中插入一些针对爬行动物的信息......

干杯:)

编辑:

我以为我必须使用Check Constraint(在我的前两个答案下面确认 - 欢呼!),但我不知道如何(例如,sql语法引用Animals表)。

更新

亚历克斯有一篇非常好的帖子(下面),对一些建议进行基准测试......非常好的阅读!

7 个答案:

答案 0 :(得分:7)

我运行了一个小基准测试 - 在这种情况下,使用UDF的方法运行速度差了近100倍。

CPU时间中FK的开销= 375 ms - 297 ms = 78 ms

UDF在CPU时间内的开销= 7750 ms - 297 ms = 7453 ms

这是Sql代码......

- 设置一个128K行的辅助表号:

CREATE TABLE dbo.Numbers(n INT NOT NULL PRIMARY KEY)
GO
DECLARE @i INT;
SET @i = 1;
INSERT INTO dbo.Numbers(n) SELECT 1;
WHILE @i<128000 BEGIN
  INSERT INTO dbo.Numbers(n)
    SELECT n + @i FROM dbo.Numbers;
  SET @i = @i * 2;
END;
GO

- 表格

CREATE TABLE dbo.Animals
(AnimalId INT NOT NULL IDENTITY PRIMARY KEY,
AnimalType TINYINT NOT NULL, -- 1: Mammal, 2:Reptile, etc..
Name VARCHAR(30))
GO
ALTER TABLE dbo.Animals
ADD CONSTRAINT UNQ_Animals UNIQUE(AnimalId, AnimalType)
GO
CREATE FUNCTION dbo.GetAnimalType(@AnimalId INT)
RETURNS TINYINT
AS
BEGIN
DECLARE @ret TINYINT;
SELECT @ret = AnimalType FROM dbo.Animals
  WHERE AnimalId = @AnimalId;
RETURN @ret;
END
GO
CREATE TABLE dbo.Mammals
(AnimalId INT NOT NULL PRIMARY KEY,
SomeOtherStuff VARCHAR(10),
CONSTRAINT Chk_AnimalType_Mammal CHECK(dbo.GetAnimalType(AnimalId)=1)
);
GO

---用UDF填充:

INSERT INTO dbo.Animals
  (AnimalType, Name)
SELECT 1, 'some name' FROM dbo.Numbers;
GO
SET STATISTICS IO ON
SET STATISTICS TIME ON
GO
INSERT INTO dbo.Mammals
(AnimalId,SomeOtherStuff)
SELECT n, 'some info' FROM dbo.Numbers;

结果是:

SQL Server parse and compile time: 
CPU time = 0 ms, elapsed time = 2 ms.
Table 'Mammals'. Scan count 0, logical reads 272135, 
    physical reads 0, read-ahead reads 0, lob logical reads 0, 
    lob physical reads 0, lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 441, physical reads 0, 
    read-ahead reads 0, lob logical reads 0, lob physical reads 0, 
    lob read-ahead reads 0.

SQL Server Execution Times:
    CPU time = 7750 ms,  elapsed time = 7830 ms.

(131072 row(s) affected)

---用FK填充:

CREATE TABLE dbo.Mammals2
(AnimalId INT NOT NULL PRIMARY KEY,
AnimalType TINYINT NOT NULL,
SomeOtherStuff VARCHAR(10),
CONSTRAINT Chk_Mammals2_AnimalType_Mammal CHECK(AnimalType=1),
CONSTRAINT FK_Mammals_Animals FOREIGN KEY(AnimalId, AnimalType)
  REFERENCES dbo.Animals(AnimalId, AnimalType)
);

INSERT INTO dbo.Mammals2
(AnimalId,AnimalType,SomeOtherStuff)
SELECT n, 1, 'some info' FROM dbo.Numbers;

结果是:

SQL Server parse and compile time: 
   CPU time = 93 ms, elapsed time = 100 ms.
Table 'Animals'. Scan count 1, logical reads 132, physical reads 0,
    read-ahead reads 0, lob logical reads 0, lob physical reads 0, 
    lob read-ahead reads 0.
Table 'Mammals2'. Scan count 0, logical reads 275381, physical reads 0,
   read-ahead reads 0, lob logical reads 0, lob physical reads 0, 
   lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 441, physical reads 0,
   read-ahead reads 0, lob logical reads 0, lob physical reads 0, 
   lob read-ahead reads 0.

SQL Server Execution Times:
   CPU time = 375 ms,  elapsed time = 383 ms.

- 没有任何完整性的填充:

CREATE TABLE dbo.Mammals3
(AnimalId INT NOT NULL PRIMARY KEY,
SomeOtherStuff VARCHAR(10)
);
INSERT INTO dbo.Mammals3
(AnimalId,SomeOtherStuff)
SELECT n,  'some info' FROM dbo.Numbers;

结果是:
    SQL Server解析和编译时间:        CPU时间= 1 ms,经过时间= 1 ms。

SQL Server Execution Times:
   CPU time = 0 ms,  elapsed time = 66 ms.
Table 'Mammals3'. Scan count 0, logical reads 272135, physical reads 0,
    read-ahead reads 0, lob logical reads 0, lob physical reads 0,
    lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 441, physical reads 0, 
    read-ahead reads 0, lob logical reads 0, lob physical reads 0, 
    lob read-ahead reads 0.

SQL Server Execution Times:
   CPU time = 297 ms,  elapsed time = 303 ms.

(131072 row(s) affected)

CPU时间中FK的开销= 375 ms - 297 ms = 78 ms
CPU时间中的UDF开销= 7750 ms - 297 ms = 7453 ms

答案 1 :(得分:6)

对动物有一个独特的约束(AnimalId,AnimalType) 将AnimalType添加到哺乳动物,并使用检查约束以确保它始终为1。 让FK参考(AnimalId,AnimalType)。

答案 2 :(得分:2)

您可以在列上创建CHECK CONSTRAINT。

ALTER TABLE Mammals
ADD CONSTRAINT CHK_AnimalType CHECK (dbo.fnGetAnimalType(animalId) = 1 );

现在你需要一个函数fnGetAnimalType,它将返回给定animalId的animalType。

这里有更多info from MSDN

答案 3 :(得分:1)

为了给予强有力的保证,您需要两种检查限制。如果您只限制Mammals某人可能会更新Animals.AnimalType并使数据处于不一致状态。

答案 4 :(得分:0)

我想你想在Mammals表中使用Check约束。

http://msdn.microsoft.com/en-us/library/ms188258.aspx

答案 5 :(得分:0)

这听起来像是表继承 - 我最近问了一个问题(无法链接,因为我太新了!),其答案导致找到this solution

我正在使用货币交易,其中交易是父表,交易类型(如支票,银行转账和CC)是子表。使用事务类型,外键约束和计算列的查找表,我能够对每个子表强制执行类型约束。

查看文章了解实施细节。

答案 6 :(得分:0)

这是一种替代方法,它基于&#34; Enforcing Complex Constraints with Indexed Views&#34;中讨论的技术。强制执行AnimalType约束。这种方法的优点是它避免了子类型表中的额外列;然而,它比AlexKuznetsov's answer中呈现的复合外键慢(尽管远不如UDF方法那么慢)。

我运行了与AlexKuznetsov相同的一系列测试,但是将行数从131,072增加到1,048,576。以下是结果摘要:

-- No integrity check:                         2488 ms.
-- With composite foreign key:                 4404 ms.
-- With indexed view and unique index:         7063 ms. <- new
-- With check constraint calling scalar UDF:  78304 ms.

架构定义:

CREATE TABLE dbo.Mammals4
(
    AnimalId INT NOT NULL PRIMARY KEY
        REFERENCES dbo.Animals (AnimalId),
    SomeOtherStuff VARCHAR(10)
);

CREATE TABLE dbo.TwoRows   -- can be reused for other similar indexed views
(
    n TINYINT NOT NULL PRIMARY KEY
)

INSERT INTO dbo.TwoRows
VALUES (1), (2)

GO

CREATE VIEW dbo.CK_Mammals4 WITH SCHEMABINDING
AS
    SELECT M.AnimalId
    FROM dbo.Mammals4 M
        JOIN dbo.Animals A
            ON A.AnimalId = M.AnimalId
        CROSS JOIN dbo.TwoRows
    WHERE A.AnimalType != 1

GO

CREATE UNIQUE CLUSTERED INDEX CKIX_Mammals4
ON dbo.CK_Mammals4 (AnimalId)

测试和结果:

-- No integrity check:

INSERT INTO dbo.Mammals3 (AnimalId, SomeOtherStuff)
SELECT n, 'some info' FROM dbo.Numbers;

Table 'Mammals3'. Scan count 0, logical reads 2969171, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 1724, physical reads 3, read-ahead reads 1720, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 2247 ms,  elapsed time = 2488 ms.

-- With composite foreign key:

INSERT INTO dbo.Mammals2 (AnimalId, AnimalType, SomeOtherStuff)
SELECT n, 1, 'some info' FROM dbo.Numbers;

Table 'Animals'. Scan count 1, logical reads 1432, physical reads 3, read-ahead reads 1428, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Mammals2'. Scan count 0, logical reads 3163291, physical reads 3, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 1724, physical reads 3, read-ahead reads 1720, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 3822 ms,  elapsed time = 4404 ms.

-- With indexed view and unique index:

INSERT INTO dbo.Mammals4 (AnimalId, SomeOtherStuff)
SELECT n, 'some info' FROM dbo.Numbers

Table 'CK_Mammals4'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Animals'. Scan count 2, logical reads 4953, physical reads 6, read-ahead reads 4945, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Worktable'. Scan count 2, logical reads 2978842, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Mammals4'. Scan count 0, logical reads 3162616, physical reads 3, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 1724, physical reads 3, read-ahead reads 1720, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 6209 ms,  elapsed time = 7063 ms.

-- With check constraint calling scalar UDF:

INSERT INTO dbo.Mammals (AnimalId, SomeOtherStuff)
SELECT n, 'some info' FROM dbo.Numbers;

Table 'Mammals'. Scan count 0, logical reads 2969171, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
Table 'Numbers'. Scan count 1, logical reads 1724, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

 SQL Server Execution Times:
   CPU time = 77424 ms,  elapsed time = 78304 ms.