Mysql 常用统计语句总结

统计今天的数据:
select * from 表名 where to_days(时间字段名) = to_days(now());
昨天
SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) <= 1
3、7天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)
4、近30天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)
5、本月
SELECT * FROM 表名 WHERE DATE_FORMAT( 时间字段名, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )
6、上一月
SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( 时间字段名, '%Y%m' ) ) =1
7、查询本季度数据
select * from `ht_invoice_information` where QUARTER(create_date)=QUARTER(now());
8、查询上季度数据
select * from `ht_invoice_information` where
QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
9、查询本年数据
select * from `ht_invoice_information` where YEAR(create_date)=YEAR(NOW());
10、查询上年数据
select * from `ht_invoice_information` where year(create_date)=year(date_sub(now(),interval 1 year));
其他
一、使用SQL语句进行区间分组统计查询 (区间分组统计查询需要使用到 elt,interval)
案例1:根据学生的分数段统计各个分数段的学生总数
统计各个分数段的学生人数
比如:统计 <50, 50-60, 60-70, 70-80, 80-90, 90-100 的分数区间内的人数
利用interval划出6个区间,在利用elt函数将6个区间分别返回一个列名,SQL如下:
select elt(
interval(score,0,50,60,70,80,90),
‘<50’,‘50-60’,‘60-70’,‘70-80’,‘80-90’,‘90-100’
) as score_level ,count(*) as counts
from class
group by elt(
interval(score,0,50,60,70,80,90),
‘<50’,‘50-60’,‘60-70’,‘70-80’,‘80-90’,‘90-100’
);

1、查询表的数据量大小

select table_name,(data_length + index_length)/1024/1024as table_mb,table_rows

from information_schema.tables

where table_schema='数据库名';

2、MySQL查询阻塞语句

select r.trx_id waiting_trx_id, r.trx_mysql_thread_Id waiting_thread,

r.trx_query waiting_query, b.trx_id blocking_trx_id,

b.trx_mysql_thread_id blocking_thread, b.trx_query blocking_query

from information_schema.innodb_lock_waits w innerjoin information_schema.innodb_trx b on b.trx_id = w.blocking_trx_id

innerjoin information_schema.innodb_trx r on r.trx_id = w.requesting_trx_id;

3、统计数据库中访问量前10的IP

SELECT

SUBSTRING_INDEX(host, ':', 1) AS ip, COUNT(*)

FROM

information_schema.processlist

GROUPBY ip

ORDERBYCOUNT(*) DESC

LIMIT 10;

猜你喜欢

转载自blog.csdn.net/weixin_30219751/article/details/128652970
今日推荐