mysql的关键字

去重:distinct关键字

解释:所有的字段一模一样才能去重

select  distinct * from work

去除name和score 一样的并且显示name 和score字段

select distinct name,score from work

去除name一样的并且显示name字段

select distinct name from work

别名as(可以省略)

  • 什么时候用别名
    1. 查询涉及多个表
    2. 用于查询函数
    3. 把两个列和更多列放在一起
    4. 列名可读性差

别名有表别名和列别名

就是个表取名字和列取名字

列别名

select score a ,name b from work

表别名

select * from work as c

where关键字

(字句限定返回值)

  • 执行顺序
    1. 从左到右执行+++++++排除比较多的,就放第一个
select * from work where in(12,23) and score=15 and name="张三"

比较运算符:not(!) and(&&) or(||)

条件选择的语句

——非(不是) 和 或

< >= <= = <>(!=)基本比较运算符 判断字符串 数字 日期的大小。

select * from work where score>60
select * from work where name <> "张三"

赋值运算符 :=

限制列范围的语句

语句:**where 列名 between val1 and val2; **是一个闭区间

select * from work where score between 20 and 80;

语句:where 列名 in (值1, 值2, ...);判断列的值是否在指定的集合中

select *from work where score in(20,30,55)

非空判断

判断列的值是否为空

语句:**where 列名 is null; **

select * form work where score is null

语句:**where 列名 is not null; **

select *from work where score is not null

like 执行通配查询/模糊查询

% 表示零或多个任意的字符

_ 表示一个任意的字符

语法:**where 列名 like '_%'; **

select *from work where name="张%"

order by关键字

语法:order by 列名

order by(升序)asc 可省略

order by desc 降序

注意:当 order by 子句中有使用了带引号的别名时,无法排序

如果数据量小则在内存中进行,如果数据量大则需要使用磁盘

select *from work  order by  score asc

MySQL分页

Limit 显示数据个数

select *from work limit 5

Limit 起始位置,显示数据个数

select *from work limit(1,5)

使用 group by 子句对结果集进行显式分组

  • 分组后的结果集隐式按升序排列

  • 如果查询列表中使用了聚合函数,或者 select 语句中使用了 group by 子句,则要求出现在

select 列表中的字段,

要么使用聚合函数或 group_concat() 包起来

**要么必须出现在 group by子句中 **

select sex,count(*) from stu group by sex;

使用 having 子句对分组进行过滤

having 与group by结合使用,用于将分组后的结果进一步过滤

select classid,sum(score) -- 要查询的数据
from stu -- 要查询的表
where classid is not null -- 去除表中不符合条件的数据
group by classid -- 根据班级分组
having sum(score) > 100   -- 对分组后的结果进行过滤
order by sum(score) desc; -- 按照总分进行排序

聚合函数

-count(*);可以获取查询的结果记录条数

-- max():获取最大值

-- min():获取最小值

-- avg():获取平均值

-- sum():指定字段求和

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。