mysql - 这个Mysql条件连接可能吗?

标签 mysql database-design

我在这里做了一些搜索,但找不到答案,所以我想问一下这是否可能......

我想根据数据库中字段的值创建条件联接。例如,如果值为 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/

相关文章:

mysql - mysql中的分组依据遵循顺序

mysql - 管道分隔与单独的行

php - 为什么我的 PHP 查询在页面加载时执行两次?

sql - 当涉及到数据库列时,您是否更喜欢详细的命名?

sql - 用户事件的数据库结构是否正确?

MySql 最佳实践 : List/Array in Single Field, 多个字段或第二个表

php - 使用 for 循环组合 PHP 优化 MYSQL 查询 while 循环输出

php - php 中的注册页面数据库中的值未更新

sql-server - 具有软删除列的表的唯一约束

database-design - Prolog 中的知识表示 - 如何存储数据?