当我执行以下代码时,出现关系“产品”不存在的错误。
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);
关于sql - PostgreSQL 错误 : relation "products" does not exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35103606/