码迷,mamicode.com
首页 > 数据库 > 详细

PostgreSQL 约束

时间:2020-03-27 19:58:40      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:class   运算符   exclude   通用   生成   prim   重复   check   标识   

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;

 

PostgreSQL 约束

标签:class   运算符   exclude   通用   生成   prim   重复   check   标识   

原文地址:https://www.cnblogs.com/wangnengwu/p/12583824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!