我有一张桌子,用来存放带有翻译和发音的词组。
我对提供translation
不感兴趣(这就是为什么我在翻译列上删除了NOT NULL的原因),但我想为所有插入内容提供pronunciation
。
CREATE TABLE phrase (
id SERIAL UNIQUE PRIMARY KEY,
phrase TEXT NOT NULL,
translation TEXT,
pronunciation TEXT,
created timestamptz NOT NULL DEFAULT now(),
modified timestamptz,
);
但是,其他用户可能想添加translation
而不是pronunciation
,或者他们想用数据填充这两列。由他们决定。
但是我希望至少提供一列。
“无论您提供的用户是translation
还是pronunciation
,至少要提供二者之一。如果两者都为空,则不插入。如果其中之一被填充,则执行插入。”
我可以使用PHP在服务器端进行此检查和验证,但我当时在想最好还是在数据库端进行检查。我读到一些有关的内容:
constraint chk_fields check (translation is not null or pronunciation is not null)
但我不知道在CREATE TABLE
语句中的何处添加它。我可以重新创建整个表,这不是问题。
答案 0 :(得分:2)
如果要这样命名,只需将其添加为另一个“列表项”即可。
CREATE TABLE phrase (
id SERIAL UNIQUE PRIMARY KEY,
phrase TEXT NOT NULL,
translation TEXT,
pronunciation TEXT,
created timestamptz NOT NULL DEFAULT now(),
modified timestamptz,
constraint chk_fields check (translation is not null or pronunciation is not null)
);
您还可以使用ALTER TABLE
语句将约束添加到现有表中。
ALTER TABLE phrase
ADD CONSTRAINT chk_fields
CHECK (translation IS NOT NULL
OR pronunciation IS NOT NULL);
(数据必须已经满足要求。)