• mysql——约束


    非空约束:
        create table temp(
            id int not null,
            name varchar(20) not null default 'adc',
            sex char null
        )//给id,name加上非空约束
        alter table temp modify sex varchar(2) not null;//增减非空约束
        alter table temp modify sex varchar(2) default 'adc' null;//取消非空约束并且增加默认值
    唯一约束:
        create table temp(
            id int not null,
            name varchar(23),
            password varcha(23),
            constraint uq_name_pass unique(name,password)//组合约束,不仅里面的单列不能重复,而且该组合名字也不能重复。constraint:给约束命名
        );//建表同时增加约束 name和pass组合不能重复
        alter table temp add unique(name,password);//使用add给name和pass增加唯一约束
        alter table temp modify name varchar(24) unique;//使用modify给name增加唯一约束
        alter table temp drop index name;//删除约束
    主键约束:(每个表只允许一个主键,该主键可以为单列,可以为多列组合的主键,不能为空,不能重复)
        create teble temp(
            id int primary key,
            name varchar(25)
        );
        create table temp1(
            id int not null,
            name varchar(25),
            pwd varchar(15),
            constraint p_name_pwd primary key(name,pwd)//组合约束
        );//组合约束例如:成绩表(学号,课程号,成绩) 
        //成绩表中单一一个属性无法唯一标识一条记录,学号和课程号的组合才可以唯一标识一条记录
        //所以 学号和课程号的属性组是一个主键 
        alter table temp drop primary key;//删除主键约束
        alter table temp add primary key(name,pwd);//给name和pwd组合增加主键
        alter table temp modify id int primary key;//修改列为主键
        create table temp(
            id int auto_increment primary key,
            name varchar(29)
        ) ;//auto_increment设置自增,设置自增后就可以不用在插入具体值了
    外键:(外键可以重复,可以为空,)
        主表:
        create table test2(
            id int auto_increment primary key,
            name varchar(20)
        );
        从表:
        create table stu(
            id int auto_increment,
            name varchar(22),
            constaint p_id primary key(id),
            test2_id int references test2(id)
        );
        或者:
        create table stu(
            id int auto_increment primary key,
            name varchar(28),
            test2_id int,
            foreigh key(test2_id) references test2(id)
            //constaint fk_id foreigh key(test2_id) references test2(id)//改约束命名
        );
        alter table stu drop foreigh key test_id;//删除外键约束
        alter table stu add foreigh key(test_id) references test2(id);//增加外键约束
    check约束:(不适用mysql)
        
  • 相关阅读:
    BZOJ1106[POI2007]立方体大作战tet
    BZOJ4407 于神之怒加强版
    BZOJ1103: [POI2007]大都市meg
    BZOJ3170: [Tjoi2013]松鼠聚会
    Luogu 2912 [USACO08OCT]牧场散步Pasture Walking
    BZOJ1251 序列终结者- splay
    BZOJ1699: [Usaco2007 Jan]Balanced Lineup排队
    BZOJ 1005[HNOI2008]明明的烦恼
    二叉树
    [CODEVS1130]数字反转
  • 原文地址:https://www.cnblogs.com/zzy-frisrtblog/p/5732916.html
Copyright © 2020-2023  润新知