SQL约束

--1.primary key  主键约束

--区分记录的唯一性

--值不能重复,也不能为空

select database();

create table if not exists stu_1(

id int unsigned,

name varchar (20)

);

create table if not exists stu_2(

id int unsigned primary key,

primary key表示将id列设置为主键,主键具有唯一性和非空性

name varchar (20)

);

create table if not exists stu_3(

id int unsigned,

name varchar (20),

primary key (id)

另一种方法将id指定为主键

);

 

--一张表中只能有一个主键

create table if not exists stu_4(

id int unsigned primary key,

name varchar (20) primary key

);

 

--联合主键

--同时将多个字段作为一个主键来使用,多个字段联合起来的值不能重复

create table if not exists stu_5(

id int unsigned,

name varchar (20),

primary key(id,name) 

);

 

--2.auto_increasement  自动递增

create table if not exists stu_6(

id int unsigned primary key auto_increasement,

name varchar (20)

);

 

--3.unique 唯一约束

--保证某个字段的值永远不重复

--允许多个NULL值存在

--一张表中只能有一个主键,但是可以有多个unique

create table if not exists stu_7(

id int unsigned primary key auto_increasement,

name varchar (20) unique

name的值不能重复,但可以有多个null值,即可以空着不写

);

--4.not null 非空约束

create table if not exists stu_8(

id int unsigned primary key auto_increasement,

name varchar (20) not null

not null表示该列不允许插入null值,即插入数据时name必须有具体的值

);

--5.deafult默认值

create table if not exists stu_9(

id int unsigned primary key auto_increasement,

name varchar (20) not null,

gender enum('男',女'',“保密”); default '保密',

该枚举中的默认值为‘保密’

createdAt timestamp default current_timestamp,

updatedAt timestamp deafult current_timestamp  on update current_timestamp

updatedAt是字段的名称,通常用于记录数据的最后一次更新事件

timestamp 表字段类型,表示存储日期和时间

on update current_timestamp 当记录更新时,数据库会自动将updatedAt的值更新为当前时间

);

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值