mysql 命令 select_Mysql基础命令(二)select查询操作

条件查询

使用Where进行数据筛选结果为True的会出现在结果集里面

select 字段 from 表名 where 条件;

# 例:

select * from test_table where id > 2; # 筛选出id大于2的所有字段

比较运算符

等于=

大于>

大于等于>=

小于<

小于等于<=

不等于!=或<>

# 例:

select * from test_table where id = 2; # 筛选出id等于2的所有字段

select * from test_table where id > 2; # 筛选出所有id大于2的所有字段

....

逻辑运算符

与and

或or

非not

# 例:

select * from test_table where id > 2 and age<18; # 筛选出所有id大于2并且年龄小于18的所有字段

select * from test_table where id > 2 or age<18; # 筛选出所有id大于2或者年龄小于18的所有字段

select * from test_table where not(id > 2 and age<18); # 筛选出所有不是id>2并且年龄小于18的字段

....

模糊查询(like, rlike)

like 使用%或_来进行模糊查询

%s 表示任意多个字符

_表示一个任意字符

rlike 使用正则表达式来模糊查询

# 例:

select * from test_table where name like "小%" # 查询数据库中小开头的所有信息的所有字段

select * from test_table where name like "小_" # 查询数据库中所有小开头的两个字的所有字段

select * from test_table where name rlkie ".." # 查询数据库的两个字符的所有数据的所有字段

范围查询

in 表示在一个非连续的范围内

between …. and … 表示在一个连续的范围类

# 例

select * from test_table where id in (1,3,5) # 查询id编号为1,3,5的所有字段信息

select * from test_table where between 1 and 5 # 查询id编号为1到5之间的所有数据的所有字段信息

空判断

null 判断值是否为空

not null 判断值是否不为空

# 例:

select * from students where text is null; # 筛选出text字段为空的数据

select * from students where text is not null; # 筛选出text字段为不为空的数据

优先级

小括号>not>比较运算符> 逻辑运算符

and 比 or先运算

聚合查询

这里需要使用到聚合函数,聚合函数有

count(*) 统计数量

max(字段) 最大值

min(字段) 最小值

sum(字段) 求和

avg(字段) 平均值

# 例:

select count(*) from test_table; # 可以直接得到一共有多少个数据

select max(id) from test_table; # 可以直接得到ID字段中最大的ID值为多少

select * from test_table where id = (select max(id) from test_table); # 可以直接使用聚合函数查询最大Id的所有的字段信息

分组查询

将数据按照字段进行分组,可以使用聚合函数对分组数据进行统计,关键字group by

# 例:

alter table test_table add tab int not null default 0; # 创建一个新的字段tab 默认为0

select tab from test_table group by tab; # 按照tab进行分组

# 分组后筛选数据

select tab, count(*) from test_table group by tab having tab=0;

对比where与having

where是对from后面指定的表进行数据筛选,属于对原始数据的筛选

having是对group by的结果进行筛选

排序查询

语法:

select * from 表名 order by 字段1 asc|desc,字段2 asc|desc,...

关键字:order by

asc是从小到大排序、即升序

desc是从大到小排序、即降序

# 例:

select * from test_table order by id asc # 按照id从小到大排序

select * from test_table order bt id desc # 按照id 从大到小排序

分页查询

关键字:limit

​ start:开始的索引

​ count:取多少条数据

select * from 表名 limit start, count

# 例:

select * from test_table limit 0,5 # 去前5个数据

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值