[英]PostgreSQL Error: relation “products” does not exist
當我執行以下代碼時,我得到關系“產品”不存在錯誤。
CREATE TABLE Orders(
ORDERID serial NOT NULL PRIMARY KEY,
ORDERDATE text NOT NULL default'',
CUSTOMERID serial NOT NULL REFERENCES Customers(CUSTOMERID),
NETAMOUNT text NOT NULL default'',
TAX text NOT NULL default'',
TOTALAMOUNT text NOT NULL default''
);
CREATE TABLE Orderlines(
ORDERLINEID serial NOT NULL,
ORDERID serial NOT NULL REFERENCES Orders(ORDERID),
PROD_ID serial NOT NULL REFERENCES Products(PROD_ID),
QUANTITY text NOT NULL default'',
ORDERDATE text NOT NULL default'',
PRIMARY KEY(ORDERLINEID,ORDERID)
);
CREATE TABLE Products(
PROD_ID serial NOT NULL PRIMARY KEY,
CATEGORY text NOT NULL references Products(CATEGORY),
TITLE text NOT NULL default'',
ACTOR text NOT NULL default'',
PRICE text NOT NULL default''
);
如果與它有任何關系,我將在http://sqlfiddle.com/中進行此操作。
創建表orderlines
,尚未執行products
表的create table
。 創建所有表后,需要添加外鍵。
您應該只將主鍵列定義為serial
,而不應將外鍵列定義為-它們將引用目標表中生成的值。 插入時,您不想為FK列生成新值。
外鍵:
CATEGORY text NOT NULL references Products(CATEGORY)
之所以出錯是因為兩個原因:首先,因為category
不是products
表的主鍵。 其次,因為類別列本身沒有意義。 您可能想參考categories
表。
您的腳本也缺少customers
表。
而且您選擇了錯誤的數據類型。
text
(或varchar
)列中。 放在一起,腳本應該是這樣的:
create table customers
(
customerid serial primary key,
.... other columns
);
create table categories
(
category serial primary key,
categoryname text not null
);
CREATE TABLE Orders
(
ORDERID serial NOT NULL PRIMARY KEY,
ORDERDATE date NOT NULL, -- no text here!
CUSTOMERID integer NOT NULL, --- NO serial here!
NETAMOUNT decimal (22,4) NOT NULL, -- no text here!
TAX decimal(18,2) NOT NULL, -- no text here!
TOTALAMOUNT decimal (24,4) NOT NULL -- no text here!
);
CREATE TABLE Orderlines
(
ORDERLINEID serial NOT NULL,
ORDERID integer NOT NULL, -- NO serial here!
PROD_ID integer NOT NULL, -- NO serial here!
QUANTITY integer NOT NULL,
ORDERDATE date NOT NULL, -- NO text here!
PRIMARY KEY(ORDERLINEID,ORDERID)
);
CREATE TABLE Products
(
PROD_ID serial NOT NULL PRIMARY KEY,
CATEGORY integer NOT NULL references categories,
TITLE text NOT NULL,
ACTOR text NOT NULL,
PRICE decimal (18,2) NOT NULL
);
alter table orderlines add foreign key (orderid) REFERENCES Orders(ORDERID);
alter table orderlines add foreign key (prod_id) REFERENCES products(prod_id);
alter table orders add foreign key (customerid) REFERENCES Customers(CUSTOMERID);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.