我所使用的表的结构
id | name | age | high | gender | cls | birth | is_delete |
---|---|---|---|---|---|---|---|
1 | iron man | 28 | 179.99 | 男 | 1 | 2020-01-01 | 1 |
3 | shell | 20 | 212.22 | 男 | 1 | NULL | 0 |
4 | joy | 20 | 160.00 | 女 | 1 | 1996-01-01 | 0 |
5 | jujuboy | 18 | 141.00 | 女 | 1 | 2019-11-29 | 0 |
6 | fafa | 18 | 179.99 | 女 | 2 | 2019-11-29 | 0 |
7 | yao | 40 | 212.00 | 男 | 2 | 2019-11-29 | 0 |
8 | jr | 25 | 202.00 | 男 | 2 | 2019-11-29 | 0 |
9 | shell | 20 | 186.00 | 保密 | 3 | 2019-11-29 | 0 |
10 | jr | 25 | 182.00 | 保密 | 3 | 2019-11-29 | 0 |
11 | iron man | 28 | 199.00 | 男 | 3 | 2019-11-29 | 0 |
12 | lingo | 25 | 173.00 | 女 | 4 | 2019-11-29 | 0 |
MySql查询
select 基础语法
select * from 表名字;
select 完整语法
select 去重选项 字段列表 [as 字段别名] from 数据源 [where子句] [group by 子句] [having 子句] [order by 子句] [limit子句];
简单的用法参照上一遍文章
条件查询
使用wheree子句对表中的数据筛选,结果为True的行会出现在结果集中
语法
select * from 表名 where 条件;
select name form students where id = 1;
比较运算符
- 等于=
- 大于>
- 大于等于>=
- 小于<
- 小于等于<=
- 不等于!= or <>
select * from students where id = 6;
select * from students where age>=20;
逻辑运算符
- and
- or
- not
运算符优先级 not > and > or
select * from students where age<20 and high<180;
select * from students where age=20 or gender=2;
-- 查询18到25之间的所有学生信息
select * from students where age>18 and age<25;
-- 查询编号小于4或没被删除的学生姓名
select name from students where id<4 or is_delete=0;
-- 查询年龄不是18且不是女性的学生姓名,年龄,性别
select name,age,gender from students where not (age=18 and gender=2);
模糊查询
- like
- %表示任意个字符串
- _表示一个字符串
-- 查询姓名中 以 "s" 开始的名字
select name from students where name like 's%';
-- 查询姓名中 有 "o" 所有的名字
select name from students where name like '%o%';
-- 查询有2个字的名字
select name from students where name like '__';
-- 查询至少有5个字的名字
select name from students where name like '_____%';
- 正则表达式
. :匹配任意单个字符串
* :匹配0个或多个前一个得到的字符
[] :匹配任意一个[]内的字符,[ab]*可以匹配空字符穿、a,b、或由任意个a和b组成的字符串。
^ :匹配开头,如^s匹配以s开头的字符串
# :匹配结尾,如s$匹配以s结尾的字符串
{n} :匹配前一个字符反复n次
rlike or regexp
匹配姓名以i开头,以n结尾的字符串(表中有iron man)的信息
select * from students where name relike '^i.*n$';
select * from students where name regexp '^i.n$';
- 范围查找
-- in(1,3,8)表示在一个非连续的范围内查找
select * from students where age in (18,40);
select * from students where name in ('shell','iron man');
-- between...and...表示在一个连续的范围内查找
select * from students where high between 180 and 200;
select * from students where (age between 18 and 22) and gender=2;
-- 空判断is null
select * from students where birth is null;
select * from students where birth is not null;