我在这里做了一些搜索,但找不到答案,所以我想问一下这是否可能......
我想根据数据库中字段的值创建条件联接。例如,如果值为 1,则加入一个表;如果值为 2,则加入另一表。
这是我必须使用的一些示例数据:
Templates Table
template_id name type
1 Email Template 1
2 Page Template 2
Email Templates Table
template_id email_subject email_body
1 test test
Page Templates Table
template_id page_title page_desc
2 test page testing
因此模板表包含所有通用模板信息,其他表包含特定于模板类型的信息。
是否可以创建条件 mysql 连接,以便如果模板表中的类型为 1,则从电子邮件表中连接,如果类型为 2,则从页表中连接?
如果没有,有人可以建议更好的模板数据库设计吗?
如有任何帮助,我们将不胜感激。
谢谢
最佳答案
select t.*,
coalesce(e.email_subject, p.page_title) title_or_subject,
coalesce(e.email_body, p.page_desc) body_or_desc
from Templates t
left join EmailTemplates e on t.type=1 and e.template_id=t.template_id
left join PageTemplates p on t.type=2 and p.template_id=t.template_id
双左连接将显示所有模板,即使它无法与任一表匹配(取决于类型)。否则,如果它必须存在于表示类型的模板表中,则
select t.*,
coalesce(e.email_subject, p.page_title) title_or_subject,
coalesce(e.email_body, p.page_desc) body_or_desc
from Templates t
left join EmailTemplates e on t.type=1 and e.template_id=t.template_id
left join PageTemplates p on t.type=2 and p.template_id=t.template_id
where ((t.type = 1 and e.template_id is not null)
or (t.type = 2 and p.template_id is not null))
关于mysql - 这个Mysql条件连接可能吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5446859/