Postgres 数据库中的数据 validation/constraint

Data validation/constraint in Postgres DB

我有一个(可能)简单的问题,关于 Postgres 数据库中的数据验证。

我有以下 table:

    Column    |         Type          | Collation | Nullable | Default | Storage  | Stats target | Description
--------------+-----------------------+-----------+----------+---------+----------+--------------+-------------
 id_number    | integer               |           | not null |         | plain    |              |
 last_name    | character varying(50) |           | not null |         | extended |              |
 first_name   | character varying(50) |           | not null |         | extended |              |
 school       | character varying(50) |           | not null |         | extended |              |
 district     | character varying(50) |           | not null |         | extended |              |

创建 table

的代码
CREATE TABLE students (
id_number INTEGER PRIMARY KEY NOT NULL,
last_name VARCHAR(50) NOT NULL,
first_name VARCHAR(50) NOT NULL,
school VARCHAR(50) NOT NULL,
district VARCHAR(50) NOT NULL);

我想为列创建一个有效输入字符串(文本)列表并拒绝任何其他输入。

例如:对于“地区”列,我希望允许的唯一输入是“地区 a”、“地区 b”或“地区 c”。

我已经通读了 constraints documentation,但没有看到任何关于文本约束或使用“或”的信息。

这可能吗?如果可以,我该怎么做?

谢谢

就在 linked documentation it discusses CHECK constraints 的顶部,这就是您想要的:

CREATE TABLE students (
    ...
    district VARCHAR(50) NOT NULL CHECK (district in ('district a', 'district b', 'district c')
);

或者,您可以为选区添加单独的 table,然后使用 FOREIGN KEY 约束将选区限制为仅 districts table.[=16 中的选区=]

为此你需要类似的东西:

create table districts (
    id integer not null primary key,
    name varchar not null
)

然后:

CREATE TABLE students (
    id_number INTEGER PRIMARY KEY NOT NULL,
    last_name VARCHAR(50) NOT NULL,
    first_name VARCHAR(50) NOT NULL,
    school VARCHAR(50) NOT NULL,
    district_id integer not null references districts(id)
)

然后您将加入 districts table 以获取地区名称。 使用单独的 table 可以更轻松地获取可能的选区列表、添加新选区、删除旧选区以及更改选区名称。这也将是一种更规范化的方法,开始时可能需要做更多的工作,但后来是一个巨大的胜利。