postgresql - 为什么 `IF` 子句在 postgres `CHECK` 约束中是不可能的?

标签 postgresql ddl check-constraints

例如这个查询是否可行?

CREATE TABLE products (
    name text,
    price numeric not null,
    CHECK (IF price > 0 THEN name IS NOT NULL ELSE name IS NULL END IF)
);

更新:

好像没有

在这里https://rextester.com/l/postgresql_online_compiler

它抛出错误

Error(s), warning(s):

42601: syntax error at or near "price"

查看文档 https://www.postgresql.org/docs/current/sql-createtable.html#SQL-CREATETABLE-EXCLUDE它说

Currently, CHECK expressions cannot contain subqueries nor refer to variables other than columns of the current row. The system column tableoid may be referenced, but not any other system column.

但是IF不是子查询,不明白为什么不行


更新 2:

CREATE TABLE products (
    name text,
    price numeric not null,
    CHECK ((price > 0 AND name IS NOT NULL) OR (price <= 0 AND name IS NULL))
);

可以,但是用这种方式编写复杂的查询会很乏味

最佳答案

在 SQL 中,IF 不是子查询,也不是其他任何东西。所以它被假定为一个列名。两个(假定的)列名紧挨着排成一行是语法错误,并分配给第二个列名。

SQL 有 CASE,没有 IF。您需要使用您正在使用的语言,而不仅仅是编造您希望工作的东西。

CREATE TABLE products (
    name text,
    price numeric not null,
    CHECK (case when price > 0 THEN name IS NOT NULL ELSE name IS NULL END)
);

关于postgresql - 为什么 `IF` 子句在 postgres `CHECK` 约束中是不可能的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58204886/

相关文章:

sql - Postgresql 从 JSON 列中选择

sql - postgresql 错误 : syntax error at or near "PRIMARY"

java - org.postgresql.util.PSQLException : ERROR: syntax error on or near "session_user"

sql - 使用 for 循环插入到表中

Java PostgreSQL arrayList<Object[]> 插入代码-应用于任意数量的列

mysql - 如何在 MySQL 表上添加自定义 CHECK 约束?

sql - 将CHECK约束添加到已填充的表中

sqlite - SQLite:条件DDL语句

sql - 修改表的架构以使其继承另一个表的架构,而无需重新创建表或重新插入数据

java - 如何找到主键最大的实体?