模糊查询
模糊查询本身用like
关键字即可:
SELECT DISTINCT field_name
FROM table_name
WHERE field_name LIKE "%"#{fieldName,jdbcType=VARCHAR}"%"
这里要注意
"%"
的使用,如果不加的话,mybatis会解析错误
另外,jdbcType=BIGINT
的模糊查询存在问题
一般模糊查询都需要去重,会用到distinct
关键字,但我们的需求又希望能输出按某个字段排序的前几个,比如:按时间倒序的前五个,这个时候sql可能如下:
select distinct user_id
from table_name
where user_id like "%"#{userId,jdbcType=VARCHAR}"%" and deleted = 0
order by ctime desc
limit 5
这样写了之后会发现查询的结果不是我们想要的(不是按时间倒序的),因为这个sql语句的执行顺序是,from
—where
—select
—distinct
—order by
—limit
,这就导致我们先去重再排序,是存在问题的,应该先排序再去重,这需要使用group by
去重,而非distinct
:
select user_id
from table_name
where user_id like "%"#{userId,jdbcType=VARCHAR}"%" and deleted = 0
group by user_id
order by max(ctime) desc
limit 5
这样语句的执行顺序是from
—where
—group by
—select
—order by
—limit
关于使用
distinct
去重和group by
去重,可以参考 distinct和group by 去掉重复记录
时间范围查询
startTime
和endTime
例子:2020-07-15
<if test="startTime != null and startTime != ''">
<![CDATA[ and DATE_FORMAT(ctime, '%Y-%m-%d')>= DATE_FORMAT(#{startTime}, '%Y-%m-%d') ]]>
</if>
<if test="endTime != null and endTime != ''">
<![CDATA[ and DATE_FORMAT(ctime, '%Y-%m-%d')<= DATE_FORMAT(#{endTime}, '%Y-%m-%d') ]]>
</if>