成人在线亚洲_国产日韩视频一区二区三区_久久久国产精品_99国内精品久久久久久久

您的位置:首頁技術(shù)文章
文章詳情頁

mysql - mybatis select語句問題

瀏覽:134日期:2022-06-11 10:15:51

問題描述

消息提醒續(xù),這個(gè)消息可能是別人直接回復(fù)了你的文章,這時(shí)需要進(jìn)行數(shù)據(jù)庫操作關(guān)聯(lián)文章表獲取相應(yīng)文章的內(nèi)容【消息提醒:您的文章xxx有了新的回復(fù)】,也可能是別人回復(fù)了你的評(píng)論這時(shí)關(guān)聯(lián)的就是評(píng)論表來獲取評(píng)論的內(nèi)容【消息提醒:您的評(píng)論xxx有了新的回復(fù)】,消息點(diǎn)擊后即可出現(xiàn)顯示詳情這樣子。

數(shù)據(jù)庫表結(jié)構(gòu)如下

mysql - mybatis select語句問題

mbelongbid為消息所屬的文章的id,mbelongcid為消息所屬的評(píng)論的id。當(dāng)mbelongcid為空時(shí)說明消息是直接回復(fù)文章,此時(shí)關(guān)聯(lián)的是文章表;當(dāng)mbelongcid不為空時(shí)說明消息回復(fù)的對(duì)象是某一條評(píng)論,此時(shí)關(guān)聯(lián)的是評(píng)論表。

sql語句要怎么寫才能符合這種需求?現(xiàn)在的想法是:

select

r.*, <if test='mbelongcid == null'>`blog`.btitle</if><if test='mbelongcid != null'>`comment`.ccontent</if>

from (

select mid, mreferuid, mbelongbid, mbelongcidfrom messagewhere mid = #{_parameter}

)r, <if test='mbelongcid == null'>

`blog` where r.mbelongbid = `blog`.bid

</if> <if test='mbelongcid != null'>

`comment` where r.mbelongcid = `comment`.cid

</if>

直接這樣寫是有問題的,大致的想法就是根據(jù)mbelongcid是否為null去關(guān)聯(lián)不同的表獲取不同的字段,有沒有好的解決方案或者建議?

問題解答

回答1:

mbelongcid不是你傳入的參數(shù)的一部分,所以mybatis并不知道它到底是不是null!,你要實(shí)現(xiàn)你想要的這種邏輯應(yīng)該從數(shù)據(jù)庫端去著手,比如創(chuàng)建一個(gè)視圖,這個(gè)視圖由兩個(gè)查詢union而成。

select mid, mreferuid, ’blog’ as type, mbelongbid as ridfrom message m, blog bwhere mbelongcid is null and mbelongbid is not null and mbelongbid = b.bidunionselect mid, mreferuid, ’comment’ as type, mbelongcid as ridfrom message m, comment cwhere mbelongcid is not null and mbelongcid = c.cid

當(dāng)你寫程序遇到這種需要很奇怪的語法的時(shí)候,請(qǐng)先回顧一下設(shè)計(jì)方案,通常緣由都是設(shè)計(jì)就有問題。

數(shù)據(jù)表誰設(shè)計(jì)的?扣工資 至少要加個(gè)下劃線啊m_belong_cid,學(xué)生黨,慢慢來吧。

回答2:

我們項(xiàng)目用的是注解式SQL,遇到這類情況都是直接在Provider拼SQL解決。

回答3:

MessageMapper.xml這部分的語句如下:

mysql - mybatis select語句問題

mysql - mybatis select語句問題

message類如下:

mysql - mybatis select語句問題

相關(guān)文章: