来自 PostgreSQL 文档
To add a constraint, the table constraint syntax is used. For example:
ALTER TABLE products ADD CHECK (name <> ''); ALTER TABLE products ADD CONSTRAINT some_name UNIQUE (product_no); ALTER TABLE products ADD FOREIGN KEY (product_group_id) REFERENCES product_groups;
To add a not-null constraint, which cannot be written as a table constraint, use this syntax:
ALTER TABLE products ALTER COLUMN product_no SET NOT NULL;
为什么 ADD
后面的词对于不同类型的约束不同?
为什么唯一约束具有比检查和外键更通用的 ADD CONSTRAINT some_name
?
为什么 ALTER COLUMN
没有指定空约束,而不是 ADD CONSTRAINT some_name NOT NULL (col_name)
?
PostgreSQL 对表添加约束的语法是否不一致? 这是否属于 SQL 标准?
最佳答案
ADD
之后的词不同所以数据库知道你的意思。例如。 CHECK
引入通用 bool 条件; UNIQUE
后面是列名列表; FOREIGN KEY
后跟一个列名,REFERENCES
和一个目标表/列。如果没有这些关键字,您指的是哪种约束将是不明确的。
CONSTRAINT <i>constraint_name</i>
语法不限于唯一约束。参见 column_constraint
的定义 和 table_constraint
在 https://www.postgresql.org/docs/10/static/sql-createtable.html ;两者都允许可选的前导 CONSTRAINT <i>constraint_name</i>
命名约束。
至于NOT NULL
, 请参阅 https://www.postgresql.org/docs/10/static/ddl-constraints.html#id-1.5.4.5.6 :
A not-null constraint is always written as a column constraint. A not-null constraint is functionally equivalent to creating a check constraint
CHECK (<i>column_name</i> IS NOT NULL)
, but in PostgreSQL creating an explicit not-null constraint is more efficient. The drawback is that you cannot give explicit names to not-null constraints created this way.
我假设非空约束在内部是一种特殊情况,允许比通用 CHECK
更好的优化约束,可以使用任何 bool 表达式。
关于sql - 向表添加约束的 PostgreSQL 语法是否存在不一致?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51183026/