MySql、mybatis 技巧

2022-10-30 15:01:27 浏览数 (1)

1、查询技巧

代码语言:javascript复制
//今天
select * from 表名 where to_days(时间字段名) = to_days(now());
//昨天
SELECT * FROM 表名 WHERE TO_DAYS( NOW( ) ) - TO_DAYS( 时间字段名) <= 1
//近7天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date(时间字段名)
//近30天
SELECT * FROM 表名 where DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= date(时间字段名)
//本月
SELECT * FROM 表名 WHERE DATE_FORMAT( 时间字段名, '%Y%m' ) = DATE_FORMAT( CURDATE( ) , '%Y%m' )
//上一月
SELECT * FROM 表名 WHERE PERIOD_DIFF( date_format( now( ) , '%Y%m' ) , date_format( 时间字段名, '%Y%m' ) ) =1
//查询本季度数据
select * from 表名 where QUARTER(create_date)=QUARTER(now());
//查询上季度数据
select * from 表名 where QUARTER(create_date)=QUARTER(DATE_SUB(now(),interval 1 QUARTER));
//查询本年数据
select * from 表名  where YEAR(create_date)=YEAR(NOW());
//查询上年数据
select * from 表名 where year(create_date)=year(date_sub(now(),interval 1 year));
//查询当前这周的数据
SELECT * FROM enterprise WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now());
//查询上周的数据
SELECT * FROM enterprise WHERE YEARWEEK(date_format(submittime,'%Y-%m-%d')) = YEARWEEK(now())-1;
//查询上个月的数据
select * from 表名 where date_format(submittime,'%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m')
select * from 表名 where DATE_FORMAT(pudate,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m') ; 
select * from 表名 where WEEKOFYEAR(FROM_UNIXTIME(pudate,'%y-%m-%d')) = WEEKOFYEAR(now()) 
select * from 表名 where MONTH(FROM_UNIXTIME(pudate,'%y-%m-%d')) = MONTH(now()) 
select * from 表名 where YEAR(FROM_UNIXTIME(pudate,'%y-%m-%d')) = YEAR(now()) and MONTH(FROM_UNIXTIME(pudate,'%y-%m-%d')) = MONTH(now()) 
select * from 表名 where pudate between 上月最后一天 and 下月第一天

2、Mybatis转义

方法一:

方法二:使用<![CDATA[ ]]>符号

代码语言:javascript复制
<if test="beginTime!=null">
    AND DATE (os.show_start_time) >= DATE(#{beginTime})
</if>
<if test="endTime!=null">
    AND DATE (os.show_start_time) <![CDATA[<=]]> DATE(#{endTime})
</if>

在mybatis中<=不能使用,需要使用上面任意一种方法转义,但是>=可以使用!

0 人点赞