1.数据的增加
- 全列插入:值和表的字段顺序一一对应
insert into students values (1,'张三',20,1,1);
- 指定列插入:值和列一一对应
insert into students (name,gender,class_id) values ('大乔',4,2);
- 多行插入,批量插入:values间用 , 隔开
insert into students (name,gender) values ('小乔',4),('周瑜',2);
2.数据的删除
delete from students where id = 2; # 用where做限定条件
3.数据的更改—update
update students set age = 26 where id = 2;
4.数据的查询—select
- 查询所有字段数据
select * from students;
- 查询指定字段数据
select name,gender from students; # 多字段用逗号隔开
- 使用 as 给字段起别名(用得少,仅作用于当前语句)
select name as 名字, gender as 性别 from students;
select name 名字 ,gender 性别 from students;
- 跨表查询
select students.name, classes.name from students,classes;
- 使用 as 给表起别名(当表的名字很长,可以使用)
select s.name,s.gender from students as s;
select students.name, students.gender from students;
- 消除重复行—distinct
select gender from students; # 查询班级学生的性别
select distinct gender from students; # 查询班级有多少种性别
select distinct id,gender from students;
多个字段,只有多列的结果完全相同才能去重 - 条件查询—where
# 1.查询年龄大于18的数据
select * from students where age > 18;
# 2.查询18岁以上的女性,and逻辑运算
select * from students where age > 18 and gender = '女';
# 3.18岁以上或者身高超过180(包含)以上的数据,or逻辑运算
select * from students where age > 18 or height >= 180;
# 4.年龄不是18岁的学生的数据,not逻辑运算
select * from students where age != 18;
select * from students where not age = 18;
- 模糊查询—like 接字符串,%表示任意字符可有可无(0个或者多个), _表示任意一个字符
# 1.查询姓名中以 "小" 开始的名字
select * from students where name like "小%";
# 2.查询姓名中名字中包含 "杰"的名字
select * from students where name like "%杰%";
# 3.查询有2个字的名字
select * from students where name like"__";
# 4.正则表达式(待补充)
select * from students where name rlike ".*杰$";
- 范围查询
# 1.in 表示在一个非连续的范围内
select * from students where age in(18,34);
# 2.not in 表示不在一个非连续的范围内,取反操作
select * from students where age not in (18,34);
# 3.between ... and ...表示在一个连续的范围内 ,两边都会包含
select * from students where age between 18 and 34;
# 4.not between ... and ...表示不在一个连续的范围内
select * from students where age not between 18 and 34;
select * from students where not age between 18 and 34;
# 5.空判断 null 不能够使用比较运算符
select * from students where height is null;
select * from students where height ="";
# 6.不为空的判断
select * from students where height is not null;
select * from students where not height is null;
- 排序查询
order by 字段 默认就是升序排序 asc 可以省略
asc从小到大排列,即升序; desc从大到小排序,即降序
# 1.查询年龄在18到34岁之间的男性,按照年龄从小到大排序
select * from students where age between 18 and 34 and gender = '男' order by age asc;
# 2.order by 多个字段 order by age asc, height desc
# 查询年龄在18到34岁之间的女性,身高从高到矮排序, 如果身高相同的情况下按照年龄从小到大排序
select * from students where age between 18 and 34 and gender = 2 order by height desc,age asc;