mysql - mybatis select语句问题
问题描述
消息提醒续,这个消息可能是别人直接回复了你的文章,这时需要进行数据库操作关联文章表获取相应文章的内容【消息提醒:您的文章xxx有了新的回复】,也可能是别人回复了你的评论这时关联的就是评论表来获取评论的内容【消息提醒:您的评论xxx有了新的回复】,消息点击后即可出现显示详情这样子。
数据库表结构如下
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这部分的语句如下:
message类如下:
相关文章:
1. 老师,CSS3里面,选择一个DIV,这个DIV是以什么为原点进行旋转的啊?2. mysql每隔10来秒就有一次7、8MB的写入3. angular.js - 我用ng-repeat出来的数据为什么在IE11中只显示{{week}}?4. android-studio - android具体的错误在哪找啊,又没有具体的位置,很郁闷啊5. angular.js - angular的directive中link中element如何解决,is not a function?6. 数据库设计 - Binary Allow Null Default mysql数据库字段属性问题 ?7. docker start -a dockername 老是卡住,什么情况?8. dockerfile - [docker build image失败- npm install]9. angular.js - 使用angular-xeditable报错10. java - jstl中c标签无法解析报错如何解决