案例:创建班级表时,班级名和教室名都设置为 NOT NULL
,保证每个班级都有名称和教室。
create table myclass(
class_name varchar(20) not null,
class_room varchar(10) not null
);
说明:当设置的列没有明确设置是,默认是deffault null(可以为空),当设置为null时 ,进行插入时该列不能为空,同时如果该列没有默认值时插入必须插入不为空的列。
案例:为表中的 age
和 sex
列设置默认值:
create table tt10 (
name varchar(20) not null,
age tinyint unsigned default 0,
sex char(2) default '男'
);
DESC
查看表结构时不能看到注释,但通过 SHOW CREATE TABLE
可以看到。案例:
create table t3 (
name varchar(20) not null comment '姓名',
age tinyint unsigned not null default 0 comment '年龄',
sex char(2) default '男' comment '性别'
);
注:正常查表无法直接看到表的描述,只有通过 SHOW CREATE TABLE
可以看到。
ZEROFILL
属性可以自动填充零。虽然存储的值仍然是实际数字,但在查询时会显示为指定宽度的数字,前面补充零。案例:
desc tt3; -- 查看表结构
alter table tt3 change a a int(5) unsigned zerofill;
案例:
create table tt13 (
id int unsigned primary key comment '学号不能为空',
name varchar(20) not null
);
主键约束会确保该列的值唯一,不能重复。
案例:
create table tt21 (
id int unsigned primary key auto_increment,
name varchar(10) not null default ''
);
添加数据时出现auto_increment数值,记录的是下一次自增长的值。
未添加数据时 | 添加数据时 |
---|---|
主动修改后自增长的值发生变化:
主动修改前 | 主动修改后 |
---|---|
案例:
create table student (
id char(10) unique comment '学号,不能重复,但可以为空',
name varchar(10)
);
alter table <表名> add primary key(<列名>);
alter table <表名> drop primary key;
插入couser_id相同,id不同的(成功) |
---|
插入id相同,couser_id不同(成功) |
插入id,couser_id都相同(失败) |
此时:两个列合在一起成为一个主键。
NULL
。案例:创建学生表和班级表,班级表的 id
是主键,学生表中的 class_id
是外键,指向班级表的 id
。
create table myclass (
id int primary key,
name varchar(30) not null comment '班级名'
);
create table stu (
id int primary key,
name varchar(30) not null comment '学生名',
class_id int,
foreign key (class_id) references myclass(id)
);
该案例展示了一个商店的数据管理系统,其中有三个表:商品表、客户表和购买表。每个表都包含主外键约束来确保数据的一致性。
创建商品表、客户表和购买表:
create table goods (
goods_id int primary key auto_increment comment '商品编号',
goods_name varchar(32) not null comment '商品名称',
unitprice int not null default 0 comment '单价,单位分',
category varchar(12) comment '商品分类',
provider varchar(64) not null comment '供应商名称'
);
create table customer (
customer_id int primary key auto_increment comment '客户编号',
name varchar(32) not null comment '客户姓名',
address varchar(256) comment '客户地址',
email varchar(64) unique key comment '电子邮箱',
sex enum('男','女') not null comment '性别',
card_id char(18) unique key comment '身份证'
);
create table purchase (
order_id int primary key auto_increment comment '订单号',
customer_id int comment '客户编号',
goods_id int comment '商品编号',
nums int default 0 comment '购买数量',
foreign key (customer_id) references customer(customer_id),
foreign key (goods_id) references goods(goods_id)
);