我在插入与另一个表具有循环关系的表时遇到问题。在下面的模式中,每个表都有一个引用另一个的外键:
create table SUPPLIERS (
SName varchar(60) primary key,
SAddress varchar(60) not null,
PCategory varchar(60) unique references PRODUCTS deferrable initially deferred
);
create table PRODUCTS (
Prodname varchar(60) primary key,
SName varchar(60) unique references SUPPLIERS deferrable initially deferred,
PCategory varchar(60) not null,
Price real not null
);
现在,当我执行这些陈述时:
insert into SUPPLIERS values
('Babolat', 'Topanga', 'Sports'),
('Infusium', 'Los Angeles', 'Beauty'),
('Market Pantry', 'San Jose', 'Food'),
('Staples', 'Burbank', 'Office')
;
insert into PRODUCTS values
('Tennis racket', 'Babolat', 'Sports', 100),
('Shampoo', 'Infusium', 'Beauty', 10),
('Water', 'Market Pantry', 'Food', 3),
('Paper', 'Staples', 'Office', 20)
;
抛出以下错误:
ERROR: relation "products" does not exist
********** Error **********
ERROR: relation "products" does not exist
SQL state: 42P01
我尝试使用deferred
关键字来让服务器执行插入操作并在事务完成后执行外键检查,但仍然会抛出错误。有什么想法吗?
答案 0 :(得分:0)
ALTER TABLE SUPPLIERS DROP CONSTRAINT SUPPLIERS_fkey;
insert into SUPPLIERS values
('Babolat', 'Topanga', 'Sports'),
('Infusium', 'Los Angeles', 'Beauty'),
('Market Pantry', 'San Jose', 'Food'),
('Staples', 'Burbank', 'Office');
insert into PRODUCTS values
('Tennis racket', 'Babolat', 'Sports', 100),
('Shampoo', 'Infusium', 'Beauty', 10),
('Water', 'Market Pantry', 'Food', 3),
('Paper', 'Staples', 'Office', 20);
ALTER TABLE SUPPLIERS
ADD CONSTRAINT SUPPLIERS_fkey FOREIGN KEY (PCategory)
REFERENCES products (PCategory) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION DEFERRABLE INITIALLY DEFERRED;