
作者简介
马听,多年 DBA 实战经验,对 MySQL、 Redis、ClickHouse 等数据库有一定了解,专栏《一线数据库工程师带你深入理解 MySQL》、《Redis 运维实战》作者。
这一节,来一起聊聊 MySQL 的库表创建及增删查改,如果没有实验环境,可以参考上一节内容:CentOS 快速安装 MySQL 8.0。
CREATE DATABASE yzl;表示创建名为 yzl 的数据库
SHOW DATABASES;
可以看到我们刚才创建的数据库 yzl。
比如需要到某个 database 下面执行命令,则必须先进入到这个库,语法如下:
use yzl;下面语句可创建一张名为 student_info 的表:
create table `student_info`(
`id` int primary key auto_increment comment '主键',
`name` varchar(11) default null comment '学生姓名',
`sex` varchar(10) default null comment '学生性别',
`grade` int(10) default null comment '学生分数',
`stu_id` int(10) default null comment '学生ID',
key idx_stu_id (`stu_id`)
)engine = innodb default charset= utf8mb4;这里对上面的语句进行解释:
show tables;
如上图,就可以看到我们刚才创建的表:student_info
show create table student_info;
如上图,我们可以看到前面所创建的表 student_info 的表结构
alter table student_info add column course varchar(10) default null comment '科目';alter table 修改表的固定语法
查看表结构,确定是否添加成功:
show create table student_info;
如上图,可以看到我们刚才新增的字段 course。
alter table student_info drop column course;查看表结构,确定字段是否删除:
show create table student_info;
如图,发现 course 字段已经没有了,因此删除字段成功。
insert into student_info(stu_id,`name`,sex,grade) values (1,'aa','女',88);
insert into student_info(stu_id,`name`,sex,grade) values (2,'bb','男',80);解释一下上面的语句
按条件查询某个字段:
select `name` from student_info where stu_id = 1;
解释一下上面的语法 select ... from 查询固定语法 语句句表示 从 student_info 中查询出 stu_id = 1 这⼀行数据的 name 字段
按条件查询所有字段
select * from student_info where stu_id = 1;
查询表的所有数据
select * from student_info;
删除数据前,最好先查询出满足条件的数据(这一次要删除的是 student_info 表中 stu_id 等于 2 的记录),以确定是否是自己要删的
select * from student_info where stu_id = 2;
确定好是自己要删除的,则执行 delete 操作:
delete from student_info where stu_id = 2;解释一下上面的语法
查询数据是否被删除:
select * from student_info where stu_id = 2;
发现 student_info 表中 stu_id 等于 2 的记录已经被成功删除了。
首先查看修改之前的数据
select * from student_info where stu_id = 1;
update student_info set `name`='yy' where stu_id = 1;
解释一下上面的语法 update ... set ... where 修改数据的固定语法 表示修改 student_info 表中满足条件 stu_id = 1 语句中的 name 为 yy
查看修改之后的数据:
select * from student_info where stu_id = 1;
发现满足条件的 name 已经被修改成 yy 了。
