1、MYSQL 查询当天、昨天、本周、本月、本年度数据SQL语句
查询今天、昨天的数据
#### 查询今天的数据
select * from 表名 where to_days(时间字段) = to_days(now());
#### 查询昨天的数据
select * from 表名 where to_days(now())-to_days(时间字段) = 1;
查询近7天内数据
#### 查询近7天内数据
select * from 表名
where YEARWEEK(DATE_FORMAT(时间字段,'%Y-%m-%d')) = YEARWEEK(NOW())
#### 查询近7天内数据
select * from 表名 where date_sub(curdate(), interval 7 day) <= date(时间字段);
查询上周的数据
### 查询上周的数据
select * from 表名
where YEARWEEK(date_format(时间字段,'%Y-%m-%d')) = YEARWEEK(now())-1;
查询月数据
#### 查询当前月份数据
select * from 表名
where DATE_FORMAT(时间字段, '%Y-%m') = DATE_FORMAT(now(),'%Y-%m')
#### 查询上个月的数据
select * from 表名
where date_format(时间字段, '%Y-%m')=date_format(DATE_SUB(curdate(), INTERVAL 1 MONTH),'%Y-%m')
查询距离当前 6个月 的数据
#### 查询距离当前如今6个月的数据
select * from 表名
where 时间字段 between date_sub(now(),interval 6 month) and now();
查询当年数据
#### 查询本月内数据
select * from 表名
where DATE_FORMAT(时间字段,'%Y') = DATE_FORMAT(SYSDATE(),'%Y')
2、mybatis中的sql语句大于、小于号的转义方法
符号 | 转义 |
---|---|
’ < ’ | < ;(t和; 之间有空格,粘贴过去要删除空格) |
’ < = ’ | < ;=(t和; 之间有空格,粘贴过去要删除空格) |
’ > ’ | > ;(t和; 之间有空格,粘贴过去要删除空格) |
’ >= ’ | > ;=(t和; 之间有空格,粘贴过去要删除空格) |
’ & ’ | & ; (p和; 之间有空格,粘贴过去要删除空格) |
’ ’ ’ | &apos ;(s和; 之间有空格,粘贴过去要删除空格) |
3、mybatis中传递list参数,进行查询(foreach标签使用)
foreach循环语句
参数 | 说明 |
---|---|
collection | 要循环的集合 |
item | 集合中的一个元素 |
open | 以什么开始 |
separator | 循环内容以什么分隔 |
close | 以什么结束 |
例子:
<select id="selectListByUserIds" parameterType="List" resultMap="SysUserResult">
select * from user u
<where>
<if test="list != null">
user_id in
<foreach collection="list" item="userId" open="(" separator="," close=")">
#{userId}
</foreach>
</if>
</where>
</select>
4、根据生日查询年龄满16岁低于60岁的人
<select id="selectIsOrNo" parameterType="integer" resultType="Long">
SELECT
count( 1 )
FROM
(
SELECT
(
YEAR ( curdate( ) ) - YEAR ( t.birthday ) - 1+ ( DATE_FORMAT( t.birthday, '% m % d' ) <= ( DATE_FORMAT( curdate( ), ' % m % d' ) ) )
) age
FROM
table_name t
where birthday IS NOT NULL
) a
WHERE
a.age >= 18
AND a.age <= 60
</select>
5、根据生日 按照年龄段进行分组
<select id="selectNoJobAge" resultMap="PlatPostTopDtoResult" >
SELECT (CASE
WHEN a.age BETWEEN 18 AND 24 THEN '18~25岁'
WHEN a.age BETWEEN 25 AND 29 THEN '25~30岁'
WHEN a.age BETWEEN 30 AND 34 THEN '30~35岁'
WHEN a.age BETWEEN 35 AND 39 THEN '35~40岁'
WHEN a.age BETWEEN 40 AND 44 THEN '40~45岁'
WHEN a.age BETWEEN 45 AND 49 THEN '45~50岁'
WHEN a.age BETWEEN 50 AND 60 THEN '50~60岁'
END) AS name,
COUNT(*) 'num' FROM
(SELECT
(
YEAR ( curdate( ) ) - YEAR ( t.birthday ) - 1+ ( DATE_FORMAT( t.birthday, '% m % d' ) <= ( DATE_FORMAT( curdate( ), ' % m % d') ) )
) age
FROM
table_name t where birthday is not null and employment =0 or employment is null
) a where a.age >= 18 and a.age <= 60
GROUP BY name
</select>
说明:job_name 是字段别名
num 是数量
birthday :表中的生日 年月日
table_name 是表名