SQL语句 常用记录

1,求平均,保留2位小数:

select convert(sum(`amount`)/count(*), decimal(10,2)) as avg from {$table}; // amount为数据库某个字段

2,条件累加

sum(IF(cnt > 8, p1, 0)) AS cnt1  ; // 如果符合 cnt > 8 条件,累加p1位的参数,否则累加0; p1可以是字段名, 第二个参数也可以是字段

count(IF(cnt > 8, true, null)) AS cnt2 ; // 如果符合 cnt > 8 条件就加1, true和null固定

3,判空NULL

ifnull(ext, 0) as mon ; // ext为某个字段或者表达式

4, 时间格式化

 //格式化时间戳
FROM_UNIXTIME( 1249488000, '%Y年%m月%d' ) ;

// 转化为时间戳,无参数则为当前时间
UNIX_TIMESTAMP() 或者 UNIX_TIMESTAMP('2019-11-01') ; 

 5,批量更新

INSERT INTO {$table} (`create_time` )  values({$create_time}) ON DUPLICATE KEY update `create_time`=VALUES(`create_time`); // ON DUPLICATE KEY update后面可放多个字段,用英文逗号隔开

6,insert  ignore  into 和 replace into

// 如果已经存在相同的记录,则忽略当前新数据, 不会产生错误
insert ignore into {$table} ( `create_time`) values({$create_time});

// 替换数据, 相当于先删除旧的数据,再用新数据替换上去; 如果不存在数据,效果则跟insert into 一样
replace into {$table} ( `create_time`) values({$create_time});

7,FIND_IN_SET 函数

// 常用于某个字段存储以逗号分隔的字符串, 查询某个数是否在这个字段字符串数据中
select * from {$table} where FIND_IN_SET('8',`field`); // field 为字段名

8,mod 求余数函数

select * from {$table} where mod(uid, 500) = 23

9,判断数据库是否存在该表,避免表不存在错误

show tables from {$database} like '{$table}';

10,TO_DAYS 函数, 返回一个从年份0开始的天数

// 比如要查询昨天的数据
select * from {$table} where to_days(now())-to_days(create_time) = 1

11,instr 函数, 作用类似 like '%关键词%';

// field 是字段, $str 是要查询的串,返回串 str 的位置,没找到就是0, 找到返回大于0的数字
SELECT INSTR(name, '') FROM {$table};

SELECT *  FROM {$table} where INSTR(name, '') > 0; 作用等同:  SELECT * FROM {$table} where name like '%明%';

12,

原文地址:https://www.cnblogs.com/pyspang/p/11904122.html