1. 程式人生 > >後臺商品搜尋功能開發SQL

後臺商品搜尋功能開發SQL

在做後臺的商品搜尋功能開發時遇到了一些問題記錄下來

版本一

<select id="SelectByNameAndParentId resultMap="Base_result" parameterType="map"">

select 

<include refid="Base_column_List"/>

from mmall_product

<if test="productId !=null">

where id = #{productId}

</if>

<if test="productName !=null">
and name like {productName}

</if>

這個是有問題的如果第一個if沒有傳值過來,那麼第二個if就不是正確的sql語句

版本二

<select id="SelectByNameAndParentId resultMap="Base_result" parameterType="map"">

select 

<include refid="Base_column_List"/>

from mmall_product

where 1 = 1

<if test="productId !=null">

and id = #{productId}

</if>

<if test="productName !=null">
and name like {productName}

</if>

</select>

這個沒問題,但是為了看起來順眼我麼使用了<where>標籤

最終版本
<select id="SelectByNameAndParentId" resultMap="BaseResult" parameterType="map">
select
<include refid="Base_column_List"/>
from mmall_product
<where>
<if test="productName != null">
and name like #{productName}
</if>
<if test="productId !=null">
and id = #{id}
</id>
</where>
</map>