1.批量替换某个值
例:将users表中 id > 100的 name 里有 ‘三’ 的 改为 ‘四’
update users set name = replace (name,'三','四') where id >100;
例:将users表中 id > 100 的 name都加上 ‘_abc’后缀
update users set name = concat(name, '_abc') where id > 100;
2. 日期常用
#1. 操作获取每一天所在月的最后一天
select * from users where created_at > last_day( '2020-10-01');
#2. 计算两个日期间的差额天数(可为负数,第一个参数减第二个参数)
select datediff('2020-11-01', '2020-01-01');
#3. 将日期格式化 %Y-%m-%d %H:%i:%s
select id from user where DATE_FORMAT(p_time, '%Y-%m-%d') = DATE_FORMAT(create_time, '%Y-%m-%d') and DATE_FORMAT(p_time, '%Y-%m-%d') = '2020-12-14'
#4. 指定的日期 减去或加上 指定的时间间隔
select date_sub('2021-01-11',interval 10 day)
select date_add('2021-01-01',interval 10 day)
#5. 将时间格式的字符串(str),按照所提供的显示格式(format)转换为DATETIME类型的值
select str_to_date(str_date,'%Y-%m-%d')
#6. 数字类型转换,例如将分转成元
SELECT CAST(amount/100 AS DECIMAL(15)) as real_amount from user_amount
#7. if判断,例如 查询时根据条件显示级别
SELECT amount ,
case
when id in(SELECT id from users ) then 1
else 0
end as jibie
from user_amont
#8.查询数据是,想让结果按查询的顺序排序(结果会按照order by 里数据的顺序排序)
select * from cards where user_id in ( 333,111,222) order by filed (user_id,333,111,222)
3.高级模糊查询函数
#1. locate函数(返回位置 0就是没找到,address是字段名)
select * from tb_test where locate ('abc', address) != 0
注:当address为null时,locate ('abc', address) 将返回 null 不能用 ' != '来判断,即 locate ('abc', address) is null
注:当第一个参数为null时,也会返回null,不能用 ' != ' ,即 locate ( null , address) is null
#2.其他函数(百度查用法)
instr、find_in_set、position
网友评论