查询
1.1 基础查询
select 内容 from 表名
1.1.1 起别名(as 可以改为空格)
select user.name as uname from user
1.1.2 去重
在查询内容前加 distinct
select distinct user.name as uname from user
1.1.3 实现连接
使用 concat实现连接
select concat(last_naem,first_name) as uname from user
1.2 条件查询
select 内容 from 表名 where 条件
1.2.1 表达式条件
简单条件运算符:> < = != <> >= <=
1.2.2 逻辑表达式
逻辑表达式:&& || !
作用:连接条件表达式
1.2.3 模糊查询
模糊查询字符:
like
between and
in
is null, is not null
1.2.4 like模糊查询
查询用户名称包括字符“a”的用户
select user.name as uname from user where user.name like ‘%a%’
注意:%是通配符,代表着可能有东西,
通配符
- %:任意多个字符(包含0个字符)
- _ :任意单个字符
1.2.5 between and模糊查询
查询用户编号在100和120之间的员工信息
select user.id from user where id between 100 and 120
注意:
- 使用between and 可以提高语句简介度
- 包涵两个临界值
- 两个临界值不能交换位置
- 等价于 select user.id from user where id >= 100 and id<=120
1.2.6 in模糊查询
查询员工的工种编号是 IT_PROG、AD_Vp、AD_PRES 中的一个员工名和工种编号
select user.id user.name from user where id in ('IT_PROG', 'AD_Vp', 'AD_PRES')
含义:
用于判断某字段的值是否属于in列表中的某一项
注意:
- 等价于select user.id user.name from user where id = ‘IT_PROG’ or id= ‘AD_Vp’ or id= ‘AD_PRES’
- 使用in可以提高语句简介度
- in 列表中的值类型必须相同
1.2.7 is null 关键字
查询没有奖金的员工名
select name from user where user.pct IS NULL
查询有奖金的员工名
select name from user where user.pct IS NOT NULL
注意:
- =不能查询null值
1.2.7 安全等于<=>
查询没有奖金的员工名
select name from user where user.pct <=> null
注意:
- is null 只能判断null
- <=>即可判断数值也可判断null
1.2 排序查询
语法:
select 查询内容 from 表 (where 条件) order by 排序列表 (asc|desc)
案例:查询员工信息,按照工资由高到低
select * from user order by salary desc
注意:
- asc是升序,desc是降序,如果不写就默认升序
- order by后也支持表达式和别名以及函数
- order by也支持多条件排序、
- order by一般放到最好(除了limit子句)
案例2:按姓名的长度查询
select * from user order by LENGTH(NAME)
案例3:先按工资排序,再按编号排序
select * from user order by salary DESC,ID ASC
1.3 常见函数
- length():获取参数值的字节长度
- concat():拼接字符
- upper()、lower():把参数变成大写、小写
- substr()、substring(): 索引从1开始
substr(‘一二三四五六七’,4):截取第四个字符到最后
substr(‘一二三四五六七’,1,3):从1开始截取长度为3 - instr(string ,int ):返回子串第一次出现的索引,如果没有返回0
- trim:去掉前后空格
trim(‘a’ )去掉前后的a - lpad():用指定字符实现左填充到指定长度(超过会从右边截断)
IPAD(’刘德华‘,10,’*‘):*******刘德华 - rpad():用指定字符实现右填充到指定长度(超过会从左边截断)
IPAD(’刘德华‘,10,’‘):刘德华****** - replace() 替换(替换全部要替换的内容)
replace(‘今天今天很开心’,’今天‘,’明天‘) :明天明天很开心
1.4 数学函数
#round 四舍五入
select round(1.65):2
#ceil 向上取整,
select ceil(2.1) :3
#floor 向下取整,
select floor (2.9) :2
#truncate 截断
select truncate (1.65,1):1.6
#mod 取余
select mod (10,3):1
1.5 日期函数
1.6 其他函数
version()查看当前版本号
DATABASE()
1.7 流程控制元素
1.if函数: if
2.case函数
二、分组函数
功能:用作统计使用,又称为聚合函数或统计函数或组函数
分类: