MySQL笔记3

数据完整性(约束)

第一个不为空且唯一的属性被当做默认主键
设置主键(会增加unique属性,有重复属性无法设置主键):
alter table 表名 add primary key(属性);
删除主键(unique属性仍然保留):
alter table 表名 drop primary key;
新建两种属性都唯一的约束(两个及两个以上的字段(属性)不能同时一致,可以存在00,01,10,11会报错):alter table 表名 add constraint 约束名 unique(属性1,属性2)
添加列:alter table 表名 add 列名 约束
删除列:alter table 表名 drop column 列名
修改列:
alter table 表名 modify column 列名 类型; – 约束
alter table 表名 change 原列名 新列名 约束; – 列名,约束
添加主键:
alter table 表名 add primary key(列名);
删除主键:
alter table 表名 drop primary key;
alter table 表名 modify 列名 int, drop primary key;
添加外键:alter table 从表 add constraint 外键名称(形如:FK_从表_主表) foreign key 从表(外键字段) references 主表(主键字段);
删除外键:alter table 表名 drop foreign key 外键名称
修改默认值:ALTER TABLE testalter_tbl ALTER i SET DEFAULT 1000;
删除默认值:ALTER TABLE testalter_tbl ALTER i DROP DEFAULT;

非NULL约束

是否可空,null表示空,非字符串
not null - 不可空
null - 可空

主键约束

主键,一种特殊的唯一索引,不允许有空值,如果主键使用单个列,则它的值必须唯一,如果是多列,则其组合必须唯一。
create table tb1(
nid int not null auto_increment primary key,
num int null
)

create table tb1(
nid int not null,
num int not null,
primary key(nid,num)
)

外键约束

外键,一个特殊的索引,只能是指定内容
creat table color(
nid int not null primary key,
name char(16) not null
)
create table fruit(
nid int not null primary key,
smt char(32) null ,
color_id int not null,
constraint fk_cc foreign key (color_id) references color(nid)
)

自增约束

自增只能在创建时添加,且只能为索引主键添加,如果为某列设置自增列,插入数据时无需设置此列,默认将自增(表中只能有一个自增列)
create table tb1(
nid int not null auto_increment primary key,
num int null
)

create table tb1(
nid int not null auto_increment,
num int null,
index(nid)
)
注意:1、对于自增列,必须是索引(含主键)。
2、对于自增可以设置步长和起始值

                 show session variables like 'auto_inc%';
                 set session auto_increment_increment=2;
                 set session auto_increment_offset=10;

                 shwo global  variables like 'auto_inc%';
                 set global auto_increment_increment=2;
                 set global auto_increment_offset=10;

检查约束(MySQL不支持check)

check(属性1>0 or 属性1<100)
check(属性2=“男” or 属性2<“女”)

默认值约束

默认值,创建列时可以指定默认值,当插入数据时如果未主动设置,则自动添加默认值
create table tb1(
nid int not null defalut 2,
num int not null
)
添加默认约束
alter table 表名 modify column subject varchar(20) default “C++”;

级联更新/删除

父表中元组更新或删除等操作对子表的处理方法
三种处理方式:
1,cascade:子表随父表更新删除
2,no action:无动作
3,set null:设置为空,父表更新或删除,子表对应数据都会set null
格式:on update/delete (cascade/no action/set null)
可以同时设置更新和删除对应的操作
on update cascade on delete no action

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值