字符串函数
concat 字符拼接
select concat('字段','字段');
upper 转大写
select upper('aa');
lower 转小写
select lower('aa');
binary 区分大小写
trim 去除字符
leading 去除最左边的
select trim(leading 'x' from 'xxxbarxxx'); -> 'barxxx'
both 去除两端的
select trim(both 'x' from 'xxxbarxxx'); -> 'bar'
trailing 去除最右边的
select trim(trailing 'xyz' from 'barxxyz'); ->'barx'
lpad,rpad 左补位和右补位(原始字符,位数,补位字符)
select lpad('hi',4,'??'); -> '??hi'
select lpad('hi',1,'??'); -> 'h'
substr(str,index,num)
从str字符串的index位置截取num个字符(如果index为负数,则从尾部开始定位,然后截取指定个数字符)index从1开始
instr(str,substr) 判断substr的值是否存在str里,存在返回位置,不存在返回 0 ;
select instr('hello,world','ll'); ->3
select instr('hello,world','nb'); ->0
length(str) 返回字符串的字节数,在数据库里一个中文占 3 字节
select length('中国'); -> 6
select length('china'); -> 5
char_length(str) 返回字符串的字符数
select char_length('中国'); -> 2
select char_length('china'); -> 5
数值函数
round(x) round(x,d)
返回参数X, 其值接近于最近似的整数。在有两个参数的情况下,返回 X ,其值保留到小数点后D位,而第D位的保留方式为四舍五入。若要接保留X值小数点左边的D 位,可将 D 设为负值。
select round(10.2); -> 10
select round(10.6); -> 11
select round(14.44,1); -> 11
mod(10,2); 取余
select mod(10,2); -> 0
时间操作
now() 获取当前时间
select now();
datediff(expr,expr2) 返回起始时间 expr和结束时间expr2之间的天数。
select datediff('2018-11-13','2018-11-04'); -> '9'
date_add(‘1998-01-02’, interval 31 day); 在某个时间点上添加多少时间,例:在1996-09-16的基础上添加22年;
select date_add('1996-09-16', interval 22 year);
adddate(‘1998-01-02’, interval 31 day); 在某个时间点上添加多少时间,例:在1996-09-16的基础上添加22年;
select adddate('1996-09-16', interval 22 year);
str_to_date 字符串转日期
select str_to_date('2017-11-10','%Y-%m-%d');
-> 2017-10-10
date_format 日期转字符串
date_format();
空值操作
null的含义
数据库里的重要概念: null, 即空值
有时表中的某些字段值,数据未知或暂时不存在,取值null,null不占任何空间
任何数据类型均可以取值null
插入 null 值
假设 student 表中只有id, name 两个字段
insert into student values(1 , null); 显示插入null值
insert into student(id) values(1); 隐式插入null值
更新成 null 值
update student set name = null where id = 10;
null 条件查询
select * from student where name is null;
转换函数
字符串转日期 str_to_date
select str_to_date('2017-10-10', '%y-%m-%d');
日期转字符串 date_format
select date_format(now(), '%y');
流程控制函数
case when then case ‘目标’ when ‘条件’ then '内容’
select case 1 when 1 then 'one' when 2 then 'two' else 'more' end;
if(expr1,expr2,expr3) 三目运算符
select if(1<2,'yes ','no');
ifnull(expr1,expr2) 假如expr1 不为 null,则 ifnull() 的返回值为 expr1; 否则其返回值为 expr2。
select ifnull(1,0); -> 1
select ifnull(null,10); -> 1
** limit 子句: 表示获取第几至第几行数据,以 0 开始 **
select * from 表名 limit 4,6;
基本查询语句
基本的查询语句语法如下
select * from 表名; //显示指定表中所有数据(*表示所有,可换成指定字段);
select 字段,字段,字段 from 表名; //显示指定字段的所有数据
别名
select name as '姓名', id as '编号' from student;
别名中的 as 也可以省略
select name '姓名', id '编号' from student;
查询语句的执行顺序
- form 子句: 执行顺序为从后往前,从右到左◦数据量较少的表尽量放在后面
- where 子句: 执行顺序为自下而上,从右到左◦将能过滤掉最大量记录的条件写在where子句的最左
- group by 执行顺序从左往右分组◦最好在group by 前面使用where将不需要的记录在group by 之前过滤掉
- having 子句:消耗资源◦尽量避免使用,having会在检索出所有记录之后才对结果集进行过滤
- select 子句: 少用号,尽量取字段名称◦在解析的过程中,通过查询数据字典将号依次转换成所有的列名,这会消耗时间
- order by 子句: 执行顺序为从左到右排序,消耗资源
- limit 子句:在前面所有执行完后最后执行