数据库基础-函数

 数据库笔记链接

         数据库基础-SQL语句

         数据库基础-函数

         数据库基础-约束

        数据库基础-多表查询

1.字符串函数

数据库基础-函数_第1张图片

-- 使用方法 
select 函数名();

-- concat 字符串连接函数
select concat('hello ', 'MySQL');    -- 结果为hello MySQL


-- lower(str) 字符串全部变小写
select lower('HELlo');               -- 结果为hello
-- uooer(str) 字符串全部变大写
select upper('helLO');               -- 结果为 HELLO

-- lpad(str, n, pad) 用字符串pad填充到 str 的左侧,直到长度等于 n
select lpad('11', 5, '0');           -- 结果为 00011
-- rpad(str, n, pad) 用字符串pad填充到 str 的右侧,直到长度等于 n
select rpad('11', 5, '0');           -- 结果为 11000

select rpad('11', 5, 'ab'); -- 当长度无法填充到 n 时,超出部分自动舍去到长度变为n变为11aba

-- trim(str) 去掉首尾空格,不管中间的空格
select trim('   Hello   MySQL  ');   -- 结果 'Hello   MySQL'

-- substring(str, start, len)  截取str的start位开始长为len的字符串
select substring('12345678', 3, 5);  -- 结果为34567, 从第三位字符3开始,长度为5的字符串
-- 主要start不能从0开始




例如:
将student表中学生的学号id变为5位,不足前补0
update student set id = lpad(id, 5, '0');

2.数值函数

数据库基础-函数_第2张图片

 举例应用:

-- 生成一个6位数的随机验证码
select lpad(round(rand() * 1000000, 0), 6, '0');  -- 生成随机数,并乘1e6变成有6为整数的值
-- 用round保留0位小数,若不足6为用lpad前补0

3.日期函数

数据库基础-函数_第3张图片

select 函数名(参数); -- 直接使用

-- 查询员工入职天数并按入职天数降序排序

select name, datediff(curdate(), entrydate) as 'entrydates' from emp order by entrydates desc;

4.流程函数

数据库基础-函数_第4张图片

-- if
select if(1 + 1 == 2, 'true', 'false');  -- 返回true
select if(1 + 1 != 2, 'true', 'false');  -- 返回false

-- ifnull
select ifnull('OK', null);               -- 返回OK
select ifnull(null, 'false');            -- 返回false

-- case when then else end
-- 查询emp表中员工的姓名和工作地址(北京/上海 ---> 一线城市, 其他 ---> 二线城市)

select 
    name, 
    (case workaddress when '北京' then '一线城市' when '上海' then '一线城市' 
    else '二线城市' end)  as '工作地址'
from emp;


-- 学生表中有学号,姓名,数学,语文,英语,这几个字段
-- 打印学生信息,但大于85分打印为优秀, 大于等于60为及格,60以下为不及格


select 
    id,
    name,
    (case when math >= 85 then '优秀' when math >= 60 then '及格' else '不及格' end) '数学',
    (case when chinese >= 85 then '优秀' when chinese >= 60 then '及格' else '不及格' end) '语文',
    (case when english >= 85 then '优秀' when english >= 60 then '及格' else '不及格' end) '英语'
from students;

你可能感兴趣的:(#+数据库,数据库,android)