数据库学习视频:https://www.bilibili.com/video/av58581566/
操作数据库
#创建数据库
create database db1;
create database db1 default charset utf8; #支持中文
#操作表
show tables; #查看表
create table t1(id int,name char(10)) default charset=utf8;
create table user_info(
id int not null auto_increment primary key,
user char(10) UNIQUE,
passwd char(20),
phone int(12)
) engine=innodb default charset=utf8;
格式:
列名 类型 null, #表示可以为空
列名 类型 not null,
列名 类型 not null default 1,#不填的时候默认位1
列名 类型 not null auto_increment primary key,#默认自增,规则要求如果是自增的必须是索 引
#innodb 支持事务
#myisam myisam
#auto_increment: 表示自增
#primary key:表示约束(不能重复也不能为空) 加速查找
#一个表里只能有一个自增 也只能有一个主键
#查看表 (查)
select * from t1;
select name from t1 where id==1;
#插入数据(增)
insert into t1(id,name) values(1,'彭文瑜'); #插入数据
#更新数据(改)
update t1 set age=18; 把表里的所有age改成18
update t1 set age=18 where age=17;
#删除数据(删)
delete from t1 where id<6; #删除id小于6的数据
#清空表
delete from t1;
truncate table t1;#数据量大的时候这个比较快
#删除表
drop table t1;
#查看表怎么创建的
show create table t1 (\G) #可以加\G 表示竖着看
类型
数字
整型
int
无符号 -2^31 (-2147483,648) ~ 2^31 - 1 (2147483647)
有符号 0 ~ 4294967295
tinyint
小整数
无符号 -128 ~ 127
有符号 0 ~255
bigint
整型数据(所有数字)。存储大小为 8 个字节。
无符号 -2^63 (-9223372036854775808) ~ 2^63-1 (9223372036854775807)
有符号 0 ~ 9223372036854775807*2-1
smallint
无符号 -2^15 (-32768) ~ 2^15 - 1 (32767)
有符号 0 ~ 65535
浮点型
float
double
以上两项都有位数限制,如果要使用数位较多的浮点型:
decimal #它使用字符串方式存储到数据库,读取的室友转为数字
写法:decimal(10,5) 表示小数点前后加起来共十位,小数点后五位的浮点型数据
字符串
char(10) #不管是否插入十位数据,它都占用十个位置
varchar(10) #如果插入数据小于十位,则根据实际大小占用位数
vachar相对更省空间,char查询更快,查询的时候知道固定跳过十位,如果使用varchar则只能通过遍历一个个找,因此优化SQL时候可以通过把定长数据放在表前面,不定长的放在后面。
PS:如果数据很大,就不用直接存数据库的方法,先存到文件,然后把文件路径存储到数据库,文件一般存文件系统
时间类型
DATATIME
enum #枚举,只能使用枚举的字符串
set #集合,只能使用集合包含的字符
外键
特点:
可以节约空间
可以形成约束
写法:
create table userinfo(
uid bigint auto_increment primary key,
name varchar(32),
department_id int,
constraint fk_user_depar foreign key ("department_id",) references department("id");
create table department(
id bigint auto_increment primary key,
title char(15)
)engine=innodb default charset=utf8;
create table department(
id bigint auto_increment primary key,
title char(15)
)engine=innodb AUTO_INCREMENT=113 default charset=utf8;
AUTO_INCREMENT=113 #表示自增id从113开始
唯一索引
PS:索引都是用来加速查找的
create table t1(
id int .....,
xx int,
unique uq1 (num,xx) #唯一索引
)
如上,两条数据,num和xx不能完全相同
特点:约束不能重复(可以为空)
主键不能重复不能为空
加速查找