PostgreSQL教程:约束(主键、非空、唯一、检查约束)

淩亂°似流年 2023-10-16 05:20 123阅读 0赞

核心在于构建表时,要指定上一些约束。

约束

主键

  1. -- 主键约束
  2. drop table test;
  3. create table test(
  4. id bigserial primary key ,
  5. name varchar(32)
  6. );

非空

  1. -- 非空约束
  2. drop table test;
  3. create table test(
  4. id bigserial primary key ,
  5. name varchar(32) not null
  6. );

唯一

  1. drop table test;
  2. create table test(
  3. id bigserial primary key ,
  4. name varchar(32) not null,
  5. id_card varchar(32) unique
  6. );
  7. insert into test (name,id_card) values ('张三','333333333333333333');
  8. insert into test (name,id_card) values ('李四','333333333333333333');
  9. insert into test (name,id_card) values (NULL,'433333333333333333');

检查

  1. -- 检查约束:必须达到指定条件
  2. -- 价格的表,pricediscount_price
  3. drop table test;
  4. create table test(
  5. id bigserial primary key,
  6. name varchar(32) not null,
  7. price numeric check(price > 0),
  8. discount_price numeric check(discount_price > 0),
  9. check(price >= discount_price)
  10. );
  11. insert into test (name,price,discount_price) values ('粽子',122,12);
给已有字段添加检查约束

在 PostgreSQL 中,您可以使用以下方法来检查约束:

  1. 创建表时定义约束:在创建表时,可以使用 CHECK 子句来定义约束条件。例如,考虑以下示例表:

    CREATE TABLE employees (

    1. id SERIAL PRIMARY KEY,
    2. name VARCHAR(100),
    3. age INTEGER,
    4. CONSTRAINT check_age CHECK (age >= 18)

    );

在上面的示例中,CHECK 子句定义了一个约束条件 age >= 18,它确保了 age 列的值必须大于或等于 18。

  1. 添加约束到现有表:您还可以使用 ALTER TABLE 语句来添加约束到现有表。例如,以下示例演示如何添加一个约束到现有的 employees 表:

    ALTER TABLE employees ADD CONSTRAINT check_age CHECK (age >= 18);

这将在 employees 表上添加一个名为 check_age 的约束。

  1. 查看约束:要查看表上的约束信息,您可以使用 \d 命令或查询系统目录表。例如,使用 \d 命令查看约束信息:

    \d employees

这将显示表的结构,包括约束信息。

  1. 删除约束:如果需要删除约束,您可以使用 ALTER TABLE 语句的 DROP CONSTRAINT 子句。以下是删除约束的示例:

    ALTER TABLE employees DROP CONSTRAINT check_age;

这将从 employees 表中删除名为 check_age 的约束。

请注意,约束是用于确保数据完整性的重要工具,在设计数据库时应谨慎选择和使用约束。

默认值

一般公司内,要求表中除了主键和业务字段之外,必须要有5个字段

  1. createdcreate_idupdatedupdate_idis_delete
  2. -- 默认值
  3. create table test(
  4. id bigserial primary key,
  5. created timestamp default current_timestamp
  6. );

发表评论

表情:
评论列表 (有 0 条评论,123人围观)

还没有评论,来说两句吧...

相关阅读