您的位置:首页技术文章
文章详情页

mysql - mybatis select语句问题

【字号: 日期:2022-06-11 10:15:51浏览:47作者:猪猪

问题描述

消息提醒续,这个消息可能是别人直接回复了你的文章,这时需要进行数据库操作关联文章表获取相应文章的内容【消息提醒:您的文章xxx有了新的回复】,也可能是别人回复了你的评论这时关联的就是评论表来获取评论的内容【消息提醒:您的评论xxx有了新的回复】,消息点击后即可出现显示详情这样子。

数据库表结构如下

mysql - mybatis select语句问题

mbelongbid为消息所属的文章的id,mbelongcid为消息所属的评论的id。当mbelongcid为空时说明消息是直接回复文章,此时关联的是文章表;当mbelongcid不为空时说明消息回复的对象是某一条评论,此时关联的是评论表。

sql语句要怎么写才能符合这种需求?现在的想法是:

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>

直接这样写是有问题的,大致的想法就是根据mbelongcid是否为null去关联不同的表获取不同的字段,有没有好的解决方案或者建议?

问题解答

回答1:

mbelongcid不是你传入的参数的一部分,所以mybatis并不知道它到底是不是null!,你要实现你想要的这种逻辑应该从数据库端去着手,比如创建一个视图,这个视图由两个查询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

当你写程序遇到这种需要很奇怪的语法的时候,请先回顾一下设计方案,通常缘由都是设计就有问题。

数据表谁设计的?扣工资 至少要加个下划线啊m_belong_cid,学生党,慢慢来吧。

回答2:

我们项目用的是注解式SQL,遇到这类情况都是直接在Provider拼SQL解决。

回答3:

MessageMapper.xml这部分的语句如下:

mysql - mybatis select语句问题

mysql - mybatis select语句问题

message类如下:

mysql - mybatis select语句问题

相关文章: