SELECT lr.*
FROM life_rent lr
JOIN rent_collection rc ON lr.id = rc.rent_Id
WHERE rc.user_Id = 7 and lr.house_type=#{type};以上是mybatis中的sql,如果前端传来的type为空怎么去掉后半句and
如果前端传来的 type
为空,可以使用 <if>
标签来动态生成查询语句。可以在 SQL 语句中使用 <if>
标签,通过判断参数是否为空来动态生成 SQL 语句,例如:
SELECT lr.*
FROM life_rent lr
JOIN rent_collection rc ON lr.id = rc.rent_Id
WHERE rc.user_Id = 7
<if test="type != null and type != ''">
AND lr.house_type = #{type}
</if>
在上面的查询语句中,使用了 <if>
标签来判断参数 type
是否为空,如果不为空,则生成 AND lr.house_type = #{type}
子句,否则不会生成该子句。这样可以避免在 lr.house_type = #{type}
中出现 type
为空的情况。
如果前端传来的 type
为空,则不会生成 AND lr.house_type = #{type}
子句,查询结果会返回所有符合 rc.user_Id = 7
的租房信息。