简体   繁体   English

在同一个表中与主键链接的外键

[英]Foreign key linked with primary key in same table

I have a table Categories with columns Id, ParentId (for "subcategories" whom can have any level of nesting) and some other. 我有一个表CategoriesId, ParentId (对于“子类别”,可以有任何级别的嵌套)和其他一些。 Using SQL Server 2012 I can't make foreign key in same table, FK_Categories_Categories ( Id -> ParentId ). 使用SQL Server 2012我无法在同一个表中创建外键, FK_Categories_CategoriesId -> ParentId )。

Error message is 错误信息是

'Categories' table '类别'表
- Unable to create relationship 'FK_Categories_Categories'. - 无法创建关系'FK_Categories_Categories'。 The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Categories_Categories". ALTER TABLE语句与FOREIGN KEY SAME TABLE约束“FK_Categories_Categories”冲突。 The conflict occurred in database "pokupaykadb", table "dbo.Categories", column 'Id'. 冲突发生在数据库“pokupaykadb”,表“dbo.Categories”,列“Id”中。

That needs for cascade deletion of subcategories. 这需要级联删除子类别。 What solution can be? 什么解决方案可以? It's desirable to be a some property, like cascade deletion from another table by foreign key 最好是某个属性,比如通过外键从另一个表中删除级联

http://i.stack.imgur.com/kXiMS.png http://i.stack.imgur.com/kXiMS.png

If there are orphaned records that does not meet your constraint criteria - delete them before creating the foreign key. 如果存在不符合约束条件的孤立记录 - 在创建外键之前删除它们。

Usually there are few records which doesn't go by the new constraint and that the DBMS doesn't allow to create the constraint. 通常,很少有记录不符合新约束,并且DBMS不允许创建约束。

In the case of orphaned values, the first occurrence is provided in the error label with the value that is orphaned. 在孤立值的情况下,第一次出现在错误标签中,其值为孤立的。

It would certainly have helped to see what code you have tried to execute. 它肯定有助于查看您尝试执行的代码。 Below is a valid table definition : 以下是有效的表定义:

CREATE TABLE dbo.Categories
(
    Id int NOT NULL IDENTITY(-2147483648, 1)
        CONSTRAINT PK_Categories PRIMARY KEY
    , ParentId int NOT NULL
        CONSTRAINT FK_Categories_ParentId
        FOREIGN KEY (ParentId) REFERENCES dbo.Categories
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM