简体   繁体   English

如何通过选择另一个字段值将一个表与两个表联接

[英]How to join a table with two tables by choosing another field value

I have three tables. 我有三张桌子。 first table! 第一桌! activity with these fields: id_company , id_act , type [ blog or poll ] second table! activity包含以下字段: id_companyid_acttype [ blogpoll ]第二个表! blog with these fields: id , 'body and third table! 具有以下字段的blogid ,'body and third table! poll with these fields: 'id , 'text , answer` with these fields: 'id轮询with these fields: 'id ,“ text” , answer”

Now, I want fetch my info from activity table by join activity with blog and poll tables depend on type field. 现在,我想通过将activityblogpoll表结合起来,从activity表中获取我的信息,这取决于type字段。

activity table
-----------------------------
id_company|   id_act|   type
-----------------------------
1         |   1     |   blog
1         |   2     |   blog
2         |   3     |   blog
1         |   1     |   poll
2         |   4     |   blog
2         |   2     |   poll
3         |   5     |   blog

blog table
-------------------
id        |   body
-------------------
1         |   aaaa    
2         |   bbbb    
3         |   cccc
4         |   dddd
5         |   eeee

poll table
-----------------------------
id        |   text |   answer
-----------------------------
1         |   zzz  |   z   
2         |   xxx  |   x  
3         |   yyy  |   y

final output for id_company IN (1, 2) must like this: id_company IN (1, 2)最终输出必须像这样:

-------------------------------------------------------
id_company|   id_act|   type|   body|   text|   answer
-------------------------------------------------------
1         |   1     |   blog|   aaaa|   NULL|   NULL
1         |   2     |   blog|   bbbb|   NULL|   NULL
2         |   3     |   blog|   cccc|   NULL|   NULL
1         |   1     |   poll|   NULL|   zzz |   z
2         |   4     |   blog|   dddd|   NULL|   NULL
2         |   2     |   poll|   NULL|   xxx |   x

Please help me to write this query. 请帮我写这个查询。

Thanks. 谢谢。

Use left join with additional join condition on basis of type column from activity table 根据活动表中的类型列,将左联接与其他联接条件一起使用

select 
a.id_company,
a.id_act,
a.type,
b.body,
p.text,
p.answer
from activity a 
left join blog b on(a.id_act = b.id and a.`type` = 'blog')
left join poll p on(a.id_act = p.id and a.`type` = 'poll')
where a.id_company IN (1, 2)

Demo 演示

Sorry I don't have a database to hand to try this but this should work :- 抱歉,我没有要尝试的数据库,但这应该可以工作:-

SELECT * FROM 
(
SELECT 
    activity.id_company
  , activity.id_act
  , activity.type
  , blog.body
  , poll.text
  , poll.answers
FROM 
activity
LEFT JOIN blog ON activity.id_act = blog.id
LEFT JOIN poll ON activity.id_act = poll.id 
)
WHERE id_company IN (1, 2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM