mysql - mybatis select语句问题

查看:155
本文介绍了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, mbelongcid
from 
    message
where 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 rid
from message m, blog b
where mbelongcid  is null and mbelongbid is not null and mbelongbid = b.bid
union
select mid, mreferuid, 'comment' as type, mbelongcid as rid
from message m, comment c
where mbelongcid is not null and mbelongcid = c.cid

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

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

这篇关于mysql - mybatis select语句问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆