关系 "table" 已经存在
Relation "table" already exists
我正在构建一个 SQL 数据库并且 运行 进入错误 "relation 'sexes' already exists"。
对于发布类似问题的 SO 用户,我尝试过:注释掉约束以查看它们是否在干扰,将所有对序列/所有主键的引用更改为整数以匹配类型,删除所有表,如果他们存在。无论我做什么,错误都一样,所以我发布了我的原始代码。关于这种情况下的问题是什么,我真的可以使用一些指导。谢谢!
CREATE TABLE sexes (
id serial PRIMARY KEY,
string text NOT NULL
);
CREATE TABLE humans (
id serial PRIMARY KEY UNIQUE NOT NULL,
forename text NOT NULL,
surname text NOT NULL,
birthdate date,
sex_id integer REFERENCES sexes(id)
);
CREATE TABLE marriages (
id serial PRIMARY KEY UNIQUE NOT NULL,
partner_1_id integer REFERENCES humans(id),
partner_2_id integer REFERENCES humans(id),
marriage_date date NOT NULL,
divorce_date date NOT NULL,
CONSTRAINT divorced CHECK (marriage_date <= divorce_date),
CONSTRAINT marry_self CHECK (partner_1_id <> partner_2_id)
);
您可以使用 IF NOT EXISTS
子句:
Do not throw an error if a relation with the same name already exists. A notice is issued in this case. Note that there is no guarantee that the existing relation is anything like the one that would have been created.
CREATE TABLE IF NOT EXISTS sexes (
id serial PRIMARY KEY,
string text NOT NULL
);
Which is really strange because dropping the tables if they existed before creating new ones threw back a whole new error.
如果你想删除表,你必须按正确的顺序进行:
DROP TABLE IF EXISTS marriages;
DROP TABLE IF EXISTS humans;
DROP TABLE IF EXISTS sexes;
我正在构建一个 SQL 数据库并且 运行 进入错误 "relation 'sexes' already exists"。
对于发布类似问题的 SO 用户,我尝试过:注释掉约束以查看它们是否在干扰,将所有对序列/所有主键的引用更改为整数以匹配类型,删除所有表,如果他们存在。无论我做什么,错误都一样,所以我发布了我的原始代码。关于这种情况下的问题是什么,我真的可以使用一些指导。谢谢!
CREATE TABLE sexes (
id serial PRIMARY KEY,
string text NOT NULL
);
CREATE TABLE humans (
id serial PRIMARY KEY UNIQUE NOT NULL,
forename text NOT NULL,
surname text NOT NULL,
birthdate date,
sex_id integer REFERENCES sexes(id)
);
CREATE TABLE marriages (
id serial PRIMARY KEY UNIQUE NOT NULL,
partner_1_id integer REFERENCES humans(id),
partner_2_id integer REFERENCES humans(id),
marriage_date date NOT NULL,
divorce_date date NOT NULL,
CONSTRAINT divorced CHECK (marriage_date <= divorce_date),
CONSTRAINT marry_self CHECK (partner_1_id <> partner_2_id)
);
您可以使用 IF NOT EXISTS
子句:
Do not throw an error if a relation with the same name already exists. A notice is issued in this case. Note that there is no guarantee that the existing relation is anything like the one that would have been created.
CREATE TABLE IF NOT EXISTS sexes (
id serial PRIMARY KEY,
string text NOT NULL
);
Which is really strange because dropping the tables if they existed before creating new ones threw back a whole new error.
如果你想删除表,你必须按正确的顺序进行:
DROP TABLE IF EXISTS marriages;
DROP TABLE IF EXISTS humans;
DROP TABLE IF EXISTS sexes;