zoukankan      html  css  js  c++  java
  • Oracle-07-约束条件

    1、主键约束

    主键(Primary key 简称PK)

    主键约束=不能重复+不能为空

    一张表中只能存在一个主键,主键可以是一列也可以是多列组合(联合主键)

    主键约束可以有两种定义方式:列级约束和表级约束

    列级:

    create table student(
    id number(4) primary key,
    name varchar2(20)
    );

    表级:

    create table student(
    id number(4),
    name varchar2(20),
    constraint student_id_pk primary key(id)
    );

    约束命名:表级定义约束建议命名规则:表名_列名_约束类型

    2、非空约束

    非空约束:not null 简称NN

    注意:非空约束只能定义在列级

    create table student(
    id number(4) primary key,
    name varchar2(20) not null
    );

    3、唯一约束(unique 简称UK)

    列级:

    create table student(
    id number(4) primary key,
    name varchar2(20) not null,
    email varchar2(15) unique
    );

    表级:

    create table student(
    id number(4),
    name varchar2(20) not null,
    email varchar2(15),
    constraint student_id_pk primary key(id),
    constraint student_email_uk unique(email)
    );

    4、检查约束(check 简称CK)

    列级:

    create table student(
    id number(4) primary key,
    name varchar2(20) not null,
    email varchar2(15) unique,
    sex char(1) check(sex in('F','M'))
    );
    
    insert into student values(0001,'张三','123@qq.com','F');

    表级:

    create table student(
    id number(4),
    name varchar2(20) not null,
    email varchar2(15),
    sex char(1),
    constraint student_id_pk primary key(id),
    constraint student_email_uk unique(email),
    constraint student_sex_ck check(sex in('F','M'))
    );

    5、外键约束(foreign key  简称FK)

    外键约束定义在两张表的两个字段上(或一张表的两个字段上),用来保证两个字段关系。

    create table temp_dept(
    deptno number(2) primary key,
    dname varchar2(10) not null
    );
    
    create table temp_emp(
    empno number(4) primary key,
    ename varchar2(15) not null,
    deptno number(2),
    constraint temp_emp_deptno_fk foreign key(deptno) references temp_dept(deptno)
    );
    
    //员工表插入数据
    insert into temp_emp values(1001,'张三丰',40);
    //部门表插入数据
    insert into temp_dept values(40,'研发部');

    说明:员工表中deptno添加外键约束,数据插入有先后顺序的,一定先有部门号,再将员工分配给指定的部门

  • 相关阅读:
    python
    python
    python
    python
    python 序列化
    字典
    异常处理
    类的成员,类的特殊方法
    HTMLEditor类常用方法说明
    HTMLEditor类常用属性说明
  • 原文地址:https://www.cnblogs.com/xslzwm/p/9668866.html
Copyright © 2011-2022 走看看