mysql其他查询:统计函数,case-when-then,多表差集查询
参考:
http://c.biancheng.net/mysql/function/(编程网:MySQL函数大全)
https://www.cnblogs.com/lazyInsects/p/8006388.html(mysql统计数据)
https://www.cnblogs.com/poloyy/p/12890763.html(常用函数汇总)
时间查询
#查询2小时前的数据 select * from tableName WHERE create_time < DATE_SUB(NOW(), INTERVAL 2 HOUR) #7天前 SELECT count(id) FROM rd_track_info WHERE DATE(create_time) < DATE_SUB(CURDATE(), INTERVAL 7 DAY);
统计数据
/*按天统计*/ SELECT count(id) countNum, DATE(create_time) createTime FROM rd_track_info GROUP BY DATE(create_time) ORDER BY DATE(create_time) DESC; /*按周统计*/ SELECT count(id) countNum, WEEK(create_time) createTime FROM rd_track_info GROUP BY WEEK(create_time) ORDER BY WEEK(create_time) DESC; /*按月统计*/ SELECT count(id) countNum, MONTH(create_time) createTime FROM rd_track_info GROUP BY MONTH(create_time) ORDER BY MONTH(create_time) DESC; /*按季度统计*/ SELECT count(id) countNum, QUARTER(create_time) createTime FROM rd_track_info GROUP BY QUARTER(create_time) ORDER BY QUARTER(create_time) DESC; /*按年统计*/ SELECT count(id) countNum, YEAR(create_time) createTime FROM rd_track_info GROUP BY YEAR(create_time) ORDER BY YEAR(create_time) DESC;
case-when-then:可以整理结果字段
基本用法
#简单case函数 case sex when '1' then '男' when '2' then '女’ else '其他' end #或 case when sex = '1' then '男' when sex = '2' then '女' else '其他' end #和if else逻辑类似,命中后其他分支不会继续 #实际用法 select u.id,u.name,u.sex, (case u.sex when 1 then '男' when 2 then '女' else '空的' end )性别 from users u;
结合聚合函数
select sum(case u.sex when 1 then 1 else 0 end)男性, sum(case u.sex when 2 then 1 else 0 end)女性, sum(case when u.sex <>1 and u.sex<>2 then 1 else 0 end)性别为空 from users u; select count(case when u.sex=1 then 1 end)男性, count(case when u.sex=2 then 1 end)女, count(case when u.sex <>1 and u.sex<>2 then 1 end)性别为空 from users u;
某值在表A中不在表B中的查询
A、B两表,找出ID字段中,存在A表,但是不存在B表的数据。A表总共13w数据,去重后大约3W条数据,B表有2W条数据,且B表的ID字段有索引。
方法一:子查询_无相关性
使用 not in ,容易理解,效率低 ~执行时间为:1.395秒~
select distinct A.ID from A where A.ID not in (select ID from B)
方法二:连接
使用 left join...on... , "B.ID isnull" 表示左连接之后在B.ID 字段为 null的记录 ~执行时间:0.739秒~
select A.ID from A left join B on A.ID=B.ID where B.ID is null
方法三:子查询_有相关性
逻辑相对复杂,但是速度最快 ~执行时间: 0.570秒~
select * from A where (select count(1) as num from B where A.ID = B.ID) = 0