查询

  • where条件查询
  • 比较运算符查询
  • 逻辑运算符
  • 模糊查询
  • 范围查询
  • 空判断查询
  • 排序
  • 聚合函数
  • 分组查询
  • 内连接
  • 左连接查询
  • 右连接查询

where条件查询

select * from 表名 where 条件;

例:

select * from hero where id = 1;
比较运算符查询
大于:>
小于:<
等于:=
大于等于:>=
小于等于:<=
不等于:!= 或 <>

例:查询id大于等于2的数据

select * from hero where id >=2;
逻辑运算符
or:或关系
and:与关系
not:非关系

例:查询id大于3或者等于4的数据

select * from hero where id >3 or id = 4;
 查询id大于3但是小于9之间的数据
 select * from hero where id>3 and id<9;
 查询id不是大于3或者小于9之间的数据
 select * from hero not (id>3 and id <9);
模糊查询
like :模糊查询关键字
_:表示任意一个字符
%:表示任意多个字符

例:查询所有姓欧阳但是名字只有一个字的人

select * from hero where name like ‘欧阳_’
 查询所有姓欧阳的小朋友
 select * from hero where name like ‘欧阳%’
范围查询
between...and... :表示在一个连续范围内
in:在一个非连续的范围内

例:查询id为3到8的数据
select * from hero where id between 3 and 8;

空判断查询
is not null : 判断不为空
is null : 判断为空

例:没有名字的数据

select * from hero where name is null;
 有名字的数据
 select * from hero where name is not null;注意:
 不能使用where name = null 判断为空
 不能使用where name != null 判断不为空
 null 不等于空字符串

排序

排序语法:
select * from hero order by 列1 asc或者desc [, 列2 asc或者desc, ...]

语法说明:
先按照列1进行排序,如果列1的值相同时,则按照列2排序,以此类推

asc:升序(默认值)
 desc:降序例按照id值升序排序
 select * from hero order by id asc;
 按照年龄大小降序排序,如果年龄相同按照身高升序排序
 select * from hero order by age desc, height asc;

聚合函数

聚合函数又叫组函数,通常是对表中的数据进行组合计算,一般与分组集合使用。

count():指定列的总行数
 max():指定列的最大值
 min():指定列的最小值
 sum():指定列的和
 avg():指定列的平均值

以下表数据进行举例说明:

MySQL 使用查询的数据插入 mysql查询或_mysql

例:

select count(*) from students;
 select max(age) from students;
 select min(age) from students;
 select sum(age) from students;
 select avg(age) from students;
分组查询
group by: 对表进行分组
group_concat + group by:分组后,每个字段信息
group by +聚合函数:分组后,每个分组的统计信息
group by + having:为分组加过滤条件
group by + with rollup :为分组加总结果
group by:
 select gender from students group by gender;group_concat + group by
 select gender,group_concat(age) from students group by gender;group by + 聚合函数
 select gender,avg(age) from students group by gender;group by + having
 select gender,group_concat(age) from students group by gender having group_contant(age) > 17;group by + rollup
 select gender,count(*) from students group by gender with rollup
内连接

连接查询可以实现多个表的查询,当查询的字段来自不同的表就可以使用连接查询完成

例表1:shop

id

name

1

手机

2

电脑

3

洗衣机

例表2:prices

shop_id

Price

1

4000

2

12000

3

500

4

200

内连接语法

select 字段 from 表1 inner join 表2 on 表1.字段 = 表2.字段
 select * from shop inner join prices on shop.id = prices.shop_id;
左连接查询
左连接:以左表为主根据条件查询右表数据,如果根据条件查询右表数据不存在使用null值填充
左连接查询语法格式:
 select 字段 from 表1 left join 表2 on 表1.字段1 = 表2.字段2
 select * from shop left join prices on shop.id = prices.shop_id;
右连接查询
右连接:以右表为主根本条件查询左表数据,如果根据条件查询左表数据不存在使用null值填充
右连接查询语法格式:
 select 字段 from 表1 right join 表2 on 表1.字段1 = 表2.字段2
 select * from shop right join prices on shop.id = prices.shop_id