条件SQLite检查约束?

abithluo  于 2022-11-30  发布在  SQLite
关注(0)|答案(3)|浏览(166)

我有一个由以下SQL定义的表:

CREATE TABLE test (
  id       integer PRIMARY KEY NOT NULL UNIQUE,
  status   text NOT NULL,
  enddate  date,
  /* Checks */
  CHECK (status IN ("Current", "Complete"))
);

我想使用CHECK添加一个约束,它要求enddate为非空**,**如果status为“Complete”。
这可能吗?我使用的是SQLite v3.6.16。

mzaanser

mzaanser1#

怎么样:

CHECK (status = "Current" or (status = "Complete" and enddate is not null))
xmd2e60i

xmd2e60i2#

没有什么可以阻止您在一个表上有多个CHECK约束。IMO是最简单和最容易扩展的解决方案:

CHECK (status IN ("Current", "Complete"))
CHECK (status <> "Complete" OR enddate IS NOT NULL)

这利用了 if A then B 在逻辑上等价于 either not A or B 的事实。

sxpgvts3

sxpgvts33#

CREATE TABLE test (
  id       integer PRIMARY KEY,
  status   text NOT NULL CHECK (status IN ('Current', 'Complete')),
  enddate  date NOT NULL
);

这将在SQLite中工作,其中CHECK约束是内联编写的。我将双引号改为撇号,以便它可以在PHP中使用。

相关问题