mysql查询语法

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():指定列的平均值

以下表数据进行举例说明:
在这里插入图片描述

例:
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

idname
1手机
2电脑
3洗衣机

例表2:prices

shop_idPrice
14000
212000
3500
4200

内连接语法
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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值