非空约束:
create table temp(
id int not null,
name varchar() not null default 'adc',
sex char null
)//给id,name加上非空约束
alter table temp modify sex varchar() not null;//增减非空约束
alter table temp modify sex varchar() default 'adc' null;//取消非空约束并且增加默认值
唯一约束:
create table temp(
id int not null,
name varchar(),
password varcha(),
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() unique;//使用modify给name增加唯一约束
alter table temp drop index name;//删除约束
主键约束:(每个表只允许一个主键,该主键可以为单列,可以为多列组合的主键,不能为空,不能重复)
create teble temp(
id int primary key,
name varchar()
);
create table temp1(
id int not null,
name varchar(),
pwd varchar(),
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()
) ;//auto_increment设置自增,设置自增后就可以不用在插入具体值了
外键:(外键可以重复,可以为空,)
主表:
create table test2(
id int auto_increment primary key,
name varchar()
);
从表:
create table stu(
id int auto_increment,
name varchar(),
constaint p_id primary key(id),
test2_id int references test2(id)
);
或者:
create table stu(
id int auto_increment primary key,
name varchar(),
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)
05-28 22:44