开发者社区> 问答> 正文

根据字段不同值关联不同表,如何做?

大家好,想请教一条sql语句。
我有四个表:前三个分别为活动表(activity),博客表(blog)和课程表(course),表结构基本一样,都是发表内容的,有title和content字段,第四个表为动态表(dynamic),当用户参加活动,发表博客和学习课程的时候,都会在动态表中进行记录。
动态表中有type字段表示此条记录是用户什么行为(活动,博客,课程),itemid字段表示此条记录的行为在他们自己表中的id,如type=1,itemid=2就表示活动表中id为2的记录在动态表中留下的记录,
现在我要显示用户动态列表,根据type字段去取不同表中的title和content字段 ,用case when不太会用,想讨教一下:
我是这么写的:
`select d.id,d.uid,d.createtime,
case
when d.type==1 then //活动
select a.title,a.content from activity a where a.id=d.itemid
when d.type==2 then //博客
select b.title,b.content from blog b where b.id=d.itemid;
where d.type=3 then //课程
select c.title,c.content from course c where c.id=d.itemid
from dynamic d `
谢谢大家 !

展开
收起
落地花开啦 2016-02-15 16:01:31 4963 0
1 条回答
写回答
取消 提交回答
  • 喜欢技术,喜欢努力的人

    这样也可以:
    `select d.id,d.uid,d.createtime,

    case  
       when d.type==1 then //活动 
         a.title,a.content 
       when d.type==2 then //博客 
         b.title,b.content
       where d.type=3  then //课程 
         c.title,c.content
    end 

    from dynamic d
    left join activity a
    on a.id=d.itemid
    left join blog b
    on b.id=d.itemid
    left join course c
    on c.id=d.itemid`

    2019-07-17 18:43:23
    赞同 展开评论 打赏
问答分类:
SQL
问答地址:
问答排行榜
最热
最新

相关电子书

更多
RowKey与索引设计:技巧与案例分析 立即下载
事务、全局索引、透明分布式 立即下载
Phoenix 全局索引原理与实践 立即下载