zoukankan      html  css  js  c++  java
  • 数据库表约束操作

    在linux中创建数据库时,需要指定数据类型,其后面还可以添加一些数据约束进去,现在详细介绍一下:

    添加的约束可以再通过代码手动修改过来

    非空约束: not null

    create table tb(
        id int not null,
        name varchar(20) not null
        );

    表示此数据类型约束为非空,不能为空

    数据约束条件可以在创建数据表的时候直接添加约束条件,也可以在创建完了以后再添加,不过并不推荐

    手动添加非空约束:
    alter table tb modify id not null;
    
    手动删除非空约束:
    alter table tb modify id int;

    唯一约束:unique key    (不能重复)

    create table tb (
        id int unique key,
        name varchar(20) unique key
        );
    
    
    手动添加唯一约束:
    alter table tb add unique key(id);
    
    手动删除唯一约束:
    alter table tb drop key id;

    主键约束:primary key (非空且唯一)

      主要功能是可以唯一表示一条数据,每张表格只能有一个主键,为了帮助mysql以最快的速度查找表中的某一条数据

      当表中没有主键的时候,默认把第一个出现的非空且唯一的列,当做主键

    create table tb (
        id int prinmary key,
        name varchar(20) 
        );
    
    手动添加主键:
    alter table tb add prinmary key(id);
    
    手动删除主键:
    alter table tb drop prinmary key;
    
    
    
    
    

    自增长约束: auto_increment (在表格添加数据的时候自动生成序号)

    create table tb(
        id int primary key auto_increment,
        name varchar(20)
        );
    
    手动添加自增长约束:
    alter table tb modify int auto_increment;
    
    手动添加自增长约束:
    alter table tb modify id int;

    默认约束:default xxx (添加数据不写会自动填充内容)

    create table tb (
        id int prinmary key,
        name varchar(20),
        age int default 20
    );
    
    手动添加默认约束:
    alter table tb modify age int default 20;
    
    手动删除默认约束:
    alter table tb modify age int;

    外键约束:foreign key

      保持数据一致性,完整性实现一对多关系必须关联到主键上面,一般情况是,关联到另一张表的主键

    create table a(
        a_id int primary key auto_increment,
        a_name varchar(20) not null
    );
    
    create table b(
        b_id int primary key,
        b_name varchar(20) not null,
        fy_id int not null,
        constraint AB_id foreign key(fy_id) references a(a_id)
        );
    
    constraint   表示外键约束
    AB_id    表示外键约束的名字,用来代表这个外键约束
    
    手动添加外键约束:
    alter table b add constraint AB_id foreign key(fy_id) references a(a_id);
    
    手动删除外键约束:
    alter table b drop foreign key AB_id
  • 相关阅读:
    codeforces 616B Dinner with Emma
    codeforces 616A Comparing Two Long Integers
    codeforces 615C Running Track
    codeforces 612C Replace To Make Regular Bracket Sequence
    codeforces 612B HDD is Outdated Technology
    重写父类中的成员属性
    子类继承父类
    访问修饰符
    方法的参数
    实例化类
  • 原文地址:https://www.cnblogs.com/pywjh/p/9520227.html
Copyright © 2011-2022 走看看