今天在开发时使用choose动态拼接where后面的sql语句,以及使用到了case when then,现进行简单的记录。
1.2 choose详解MyBatis Mapper.xml的choose标签的作用类似于java中的switch语句,使用choose标签时为了避免使用大量的if元素。choose元素包含了when元素(对应java中的case语句),otherwise元素则对应java中的default语句。
1.2.1 choose元素的DTD定义备注:其中when元素可以存在多个,otherwise元素只能存在一个或零个。
1.2.2 when元素的DTD定义备注:test属性表示该when元素中的SQL被使用的测试条件。
1.2.3 otherwise元素的定义1.2.4 实例
获取查询信息,使用多个choose来动态拼凑条件。
1.3 CASE详解SELECT count(b.sfp_user_id) people,a.id,a.group_name groupName, a.group_accord_name groupAccordName,a.app_id appId,a.create_by createBy, a.create_time createTime FROM user_group a LEFT JOIN group_user b on b.user_group_id = a.id a.app_id = #{appId} GROUP BY a.group_name , a.group_accord_name ,a.app_id , a.create_by ,a.create_time ,a.id ORDER BYand a.create_by=#{userNm} and a.group_accord_name like CONCAt('%',#{keyword},'%') and (a.create_by like CONCAt('%',#{keyword},'%') or a.group_accord_name like CONCAt('%',#{keyword},'%')) people DESC,createTime DESC people ASC,createTime DESC createTime DESC
在mapper.xml文件中,需要直接给查询的数据直接赋值或者别名显示的时候需要用到CASE WHEN THEN
1.3.1 查询简单case函数(推荐)
CASE xxx WHEN ‘x’ THEN ‘x’ WHEN ‘x’ THEN ‘x’ ELSE ‘xx’ END
case搜索函数
CASE WHEN xxx = ‘x’ THEN ‘x’ WHEN xxx = ‘x’ THEN ‘x’ ELSE ‘xx’ END
扩展
select case when total > max then 2 when total < min then 1 else 0 end from ta
1.3.2 更新select a.id, deviceId, gender, CASE gender when '0' then '男' when '1' then '女' else '未知' end genderName from sfp_user a left join group_user b on a.id = b.sfp_user_id AND b.user_group_id = #{id} b.user_group_id = #{id} ORDER BY registrationTime DESCAND (a.user_code like CONCAt('%',#{keyword},'%') or a.device_id like CONCAt('%',#{keyword},'%')) AND a.gender = #{gender} AND a.city_code = #{cityCode} AND a.device_id = #{deviceId} AND (a.registration_time BETWEEN #{registrationStartTime} AND #{registrationEndTime})
UPDATE table SET xxx =(
CASE
WHEN xxx > xx THEN 'xx'
WHEN xxx > xx THEN 'xx'
ELSE 'xx'
END )
WHERe y = 'a';



