2016-03-14 53 views
0

我在插入與另一個表具有循環關係的表時遇到問題。在下面的模式中,每個表有引用其他的外鍵:無法插入到相互參照的表(PostgreSQL)中

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關鍵字來獲得服務器執行插入操作,並在之後執行外鍵檢查tran saction已完成,但仍會拋出錯誤。有任何想法嗎?

+0

爲什麼所有的供應商都擁有在首位的產品? – Shadow

+0

錯誤消息「關係不存在」很清楚。也許你用名稱周圍的雙引號創建了表格? '「產品」'是與「產品」不同的表名。 [詳見手冊](http://www.postgresql.org/docs/current/static/sql-syntax-lexical.html#SQL-SYNTAX-IDENTIFIERS)。如果是這種情況,那麼推遲將不會幫助你。但是這個設計首先對我沒有意義。你不應該有一個供應商和產品參考的分類表嗎? –

回答

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;