She*_*roz 3 postgresql foreign-keys primary-key
在我的数据库设计中,我需要一个具有递归外键关系的表,即外键引用同一个表.当我尝试使用一列时,它可以正常工作,但是当我使用两列时,它会出错.下面是示例代码和产生的错误.我们将非常感谢您的帮助.
CREATE TABLE categories (
categoryID integer ,
parentID integer ,
setID integer REFERENCES categories(categoryID,parentID),
name char(255) NOT NULL,
PRIMARY KEY(categoryID,parentID)
);
Run Code Online (Sandbox Code Playgroud)
错误:外键不同意的引用和引用列数
我用的时候
setID integer REFERENCES categories(categoryID) and
PRIMARY KEY(categoryID)
Run Code Online (Sandbox Code Playgroud)
然后它没有错误,但那不是我想要的.
你可能想要这个:
CREATE TABLE categories (
categoryID integer,
parentID integer,
setID integer,
name char(255) NOT NULL,
PRIMARY KEY (categoryID, parentID),
FOREIGN KEY (categoryID, parentID) REFERENCES categories(categoryID, parentID)
);
Run Code Online (Sandbox Code Playgroud)
CREATE TABLE categories (
categoryID integer,
parentID integer,
setID integer,
name char(255) NOT NULL,
PRIMARY KEY (categoryID, parentID),
UNIQUE (setID, parentID)
FOREIGN KEY (setID, parentID) REFERENCES categories(setID, parentID)
);
Run Code Online (Sandbox Code Playgroud)
外键的目标需要某种唯一性约束.我引用手册:
引用的列必须是引用表中不可延迟的唯一或主键约束的列.
是的,不幸的是,您试图说一个数字字段应该相当于两个数字字段。不会真的发生。
考虑一下您对 SetID 的使用。你真的需要它吗?
相反,请确保parentID 是categoryID 的外键(即表示parentID 的任何值都必须作为parentID 中对应且现有的值存在)。