动态sql 模糊查询
时间: 2023-10-26 15:22:56 浏览: 49
动态SQL是指在SQL语句中根据条件的不同而动态生成不同的SQL语句的技术。在动态SQL中,可以使用一些特定的标签和函数来处理特殊字符和实现模糊查询。
在MyBatis中,常用的动态SQL标签包括if、where、choose、when、otherwise、set、foreach等。这些标签可以根据条件的不同来决定是否包含某个SQL片段。比如,如果要进行模糊查询,可以使用concat函数将查询条件拼接成模糊匹配的格式。
下面是两种实现模糊查询的方式:
方式1:
```xml
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog where 1 = 1
<if test="title!=null">
and title like #{title}
</if>
</select>
```
在这个例子中,使用了if标签来判断是否有模糊查询的条件,如果有,则将条件拼接到SQL语句中。
方式2:
```xml
<select id="queryBlogIf" resultType="blog" parameterType="map">
select * from mybatis.blog where 1 = 1
<if test="title!=null">
and title like concat('%',#{title},'%')
</if>
</select>
```
在这个例子中,使用了concat函数将查询条件拼接成模糊匹配的格式。
通过使用这些动态SQL标签和函数,我们可以根据不同的条件来动态生成符合需求的SQL语句,实现灵活的模糊查询功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [动态SQL 模糊查询 联表查询](https://blog.csdn.net/Luckydogs3036/article/details/125130893)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [mybatis动态sql模糊查询方法](https://blog.csdn.net/niceYF/article/details/123370626)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]