插入或删除时出现外键问题

时间:2019-05-31 11:07:23

标签: postgresql foreign-keys postgresql-9.5

我下面有3张桌子

enter image description here

用户

enter image description here

和  带有外键的test.users_books

CREATE TABLE test.users_books (
  user_id int NOT NULL,
  PRIMARY KEY (user_id),
  FOREIGN KEY (user_id) REFERENCES test.users(id) ON UPDATE CASCADE ON DELETE CASCADE,
  FOREIGN KEY (user_id) REFERENCES test.books(id) ON UPDATE CASCADE ON DELETE CASCADE

);

尝试插入

INSERT INTO test.users_books values(11)

遇到错误

ERROR:  insert or update on table "users_books" violates foreign key constraint "users_books_user_id_fkey"
DETAIL:  Key (user_id)=(11) is not present in table "users".
********** Error **********

ERROR: insert or update on table "users_books" violates foreign key constraint "users_books_user_id_fkey"
SQL state: 23503
Detail: Key (user_id)=(11) is not present in table "users".

如何使用11在书本表中具有的外键将11插入此表中。 该表是否需要插入任何条件,请让我知道

0 个答案:

没有答案