我使用postgresql,并创建一些表。 有用户'表
CREATE TABLE myschem.users (
id serial NOT NULL, name character varying(255),email character varying(255)
) WITH ( OIDS=FALSE );
..还有一张书桌
CREATE TABLE myschem.books (
id serial NOT NULL, title character varying(255),author character varying(255)
) WITH ( OIDS=FALSE );
我尝试制作关系表
CREATE TABLE myschem.bookloans
(
uid integer, -- user id
bid integer, -- book id
primary key (uid, bid),
FOREIGN KEY (uid) REFERENCES myschem.users (id) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (bid) REFERENCES myschem.rooms (id) ON DELETE CASCADE ON UPDATE CASCADE
);
如何做得更好,不显示消息:
ERROR: there is no unique constraint matching given keys for referenced table "users"
? 谢谢!
答案 0 :(得分:1)
外键无法引用非唯一字段,因为它需要引用唯一行。
您需要将引用的字段设为PRIMARY KEY
;
CREATE TABLE users (
id serial NOT NULL PRIMARY KEY,
...或者只是将它UNIQUE
;
CREATE TABLE books (
id serial NOT NULL UNIQUE,
An SQLfiddle showing both versions working to create the tables