根據字段不同值關聯查詢不同表的問題

2021-07-22 05:15:11 字數 1145 閱讀 7158

我有四個表:前三個分別為活動表(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 

我喜歡這樣寫

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

根據表字段值left join 不同的表

首先說下思路吧,搗鼓了好半天,網上找到解決辦法,大概兩種方法 1.在left join 的後面將兩張表union all連線為一張表,並加上 區分表關鍵字 然後根據 區分表關鍵字 篩選我們需要的資料 2.使用兩個left join,每個left join 跟上一張表,並加上 區分表關鍵字 然後在 o...

oracle根據不同條件給字段賦不同的值

話不多說,先貼 declare cursor my cur is select t.empno,t.deptno,t.sal from scott.emp t where t.empno 7698 for update of sal 鎖定sal這一列,不允許其他session更新sal列的資料 nu...

MySQL兩表聯查,根據不同條件獲得不同資料

查詢語句 select distinct ifnull select sum 列名 from a,b where a.id b.id and a.condition condition1 and b.condition condition2 0 as 條件1下的資料 ifnull select su...