一、需求描述
自己在開發一個小程式的過程中,需要做的一個查詢是稍微比較複雜的查詢,根據使用者資訊去查詢使用者所對應的寵物資訊。
一個使用者可能對應多個寵物,所以在使用者和寵物資訊的對應關係就是一對多的關係。
二、需求分析
以前在學習mybatis的時候,大致記得mybatis裡面有級聯查詢的功能,只需要在xml檔案中寫好響應的sql和配置好響應的
查詢即可。自己立馬去百度裡面搜尋,看了幾篇博文,把以前學習的東西都記起來了,立馬進行使用。
三、解決方案
涉及輸出類,裡面包含集合型別,如下
主查詢語句如下//
<select id="userRank" resultMap="userRankResultMap">
SELECT
@rownum := @rownum + 1 user_rank,
tab.user_id,
tab.nick_name,
tab.user_name,
IFNULL(tab.avatar_url, '') avatar_url,
tab.user_experience,
tab.user_level,
tab.openid
FROM
(SELECT @rownum := 0) a,
(
SELECT
f.user_id,
f.nick_name,
f.user_name,
f.avatar_url,
f.user_experience,
f.user_level,
SUM(
IFNULL(f.user_experience, 0)
) expSum,
f.openid
FROM
app_user_info f WHERE f.status = 1
GROUP BY
f.user_id
ORDER BY
expSum DESC
) tab
</select>
查詢結果集為
<!-- 查詢結果集 -->
<resultMap id="userRankResultMap" type="applets.user.outvo.RankOutVo">
<id column="user_rank" property="userRank" jdbcType="INTEGER" />
<result column="user_id" property="userId" jdbcType="VARCHAR" />
<result column="nick_name" property="nickName" jdbcType="VARCHAR" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
<result column="avatar_url" property="avatarUrl" jdbcType="VARCHAR" />
<result column="user_experience" property="userExperience" jdbcType="INTEGER" />
<result column="user_level" property="userLevel" jdbcType="INTEGER" />
<result column="openid" property="openid" jdbcType="VARCHAR" />
<!-- 關聯查詢使用者已經領養寵物列表
ofType:指定關聯查詢的結果集中的物件型別即List中的物件型別。
collection:表示一對多當中的集合型別
column:表示主查詢和關聯查詢之間的關聯條件
-->
<collection property="petList" ofType="applets.nature.entiry.PetInfo" column="openid" select="selectPetInfo">
</collection>
</resultMap>
最後一個關聯查詢為
<!-- 排名查詢中的子查詢 -->
<select id="selectPetInfo" resultType="applets.nature.entiry.PetInfo">
SELECT pet_id, pet_type, pet_name, pet_level
FROM app_pet_info
WHERE openid = #{openid, jdbcType = VARCHAR}
AND species_type = 2
AND is_adopt = 1
ORDER BY pet_level DESC
LIMIT 3
</select>
寫好後測試結果正確。列印的日誌為先查詢第一個主查詢,關聯查詢會查詢多次。
參考文章:
https://www.cnblogs.com/yigedingzi/p/10836734.html
https://zhuanlan.zhihu.com/p/40621891