设为首页 加入收藏

TOP

Mysql基础命令(二)select查询操作
2019-09-17 18:40:47 】 浏览:35
Tags: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编号为135的所有字段信息 select * from test_table where between 1 and 5 # 查询id编号为15之间的所有数据的所有字段信息

空判断

  • 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个数据
?
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇MySQL大表优化方案 下一篇MySQL数据连表查询思路

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目