zoukankan      html  css  js  c++  java
  • PostgreSQL 约束

    NOT NULL 约束:

    默认情况下,列可以保存为 NULL 值。如果您不想某列有 NULL 值,那么需要在该列上定义此约束,指定在该列上不允许 NULL 值。

    NULL 与没有数据是不一样的,它代表着未知的数据。

    create table  company1(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null,

    address char(50),

    salary real

    );

    UNIQUE 约束:

    UNIQUE 约束可以设置列是唯一的,避免同一列出现重复值。

    create table  company1(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null  unique,

    address char(50),

    salary real);

    PRIMARY KEY:

    PRIMARY KEY 称为主键,是数据表中每一条记录的唯一标识。

    设置 UNIQUE 的列可能有多个,但是一张表只有一列可以设置 PRIMARY KEY。

    create table  company1(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null,

    address char(50),

    salary real);

    FOREIGN KEY 约束:

    FOREIGN KEY 即外键约束,指定列(或一组列)中的值必须匹配另一个表的某一行中出现的值。

    通常一个表中的 FOREIGN KEY 指向另一个表中的 UNIQUE KEY(唯一约束的键),即维护了两个相关表之间的引用完整性

    create table  company6(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null,

    address char(50),

    salary real

    );

    下面实例创建一张 DEPARTMENT1 表,并添加 3 个字段,EMP_ID 就是外键,参照 COMPANY6 的 ID:

    create table department1(

    id int primary key not null,

    dept  char(50) not null,

    emp_id  int  references company6(id)

    );

    CHECK 约束:

    CHECK 约束保证列中的所有值满足某一条件,即对输入一条记录要进行检查。如果条件值为 false,则记录违反了约束,且不能输入到表。

    create table  company1(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null,

    address char(50),

    salary real  check (salary > 0)

    );

    EXCLUSION 约束:

    EXCLUSION 约束确保如果使用指定的运算符在指定列或表达式上比较任意两行,至少其中一个运算符比较将返回 false 或 null。

    create table  company1(

    id  int  primary  key not null,

    name   text   not null,

    age  int  not null,

    address char(50),

    salary real

    exclude  using  gist

    (name with =,

    age with <>)

    );

    删除约束:

    删除约束必须知道约束名称,已经知道名称来删除约束很简单,如果不知道名称,则需要找到系统生成的名称,使用 d 表名 可以找到这些信息。

    通用语法如下:

    alter table  table_name  drop  constraint  some_name;

  • 相关阅读:
    poj3436(ACM Computer Factory)
    一位ACMer过来人的心得
    poj1459(Power Network)
    (转)网络流—最大流(Edmond-Karp算法)
    poj1611(The Suspects)
    构建之法阅读笔记01
    第三周总结
    全国疫情可视化地图
    第二周总结
    作业--数组(大数)
  • 原文地址:https://www.cnblogs.com/wangnengwu/p/12583824.html
Copyright © 2011-2022 走看看