您要么有一个电子邮件表,它的外键要么是 system_id、account_id 或 customer_id。然后你可以有一个字段来指定该外键的类型。另一个更复杂的策略是保留电子邮件表但没有外键。另一个称为 email_relation 的表,由 email_id 和外键组成。这样您就可以为所有三个表使用一个电子邮件地址。
两个表的使用示例
system
--------
s1
s2
s3
account
--------
a1
a2
a3
customer
--------
c1
c2
c3
email
------
e1 example1@a.com
e2 example2@a.com
e3 example3@a.com
e4 example4@a.com
email_relation
---------------
email_id foreign_id relation_type
e1 s1 system
e1 a1 account
e1 c1 customer
e2 c1 customer
e3 c2 customer
e4 a3 account
e4 c3 customer
如果您想要包含电子邮件地址的客户表
select c.customer_id, e.email
from customer c
left join email_relation r on (r.foreign_id = c.customer_id and relation_type = 'customer')
left join email e on (e.email_id = r.email_id)
where r.email_id is not null
如果您希望将所有电子邮件发送到系统,您还可以
select e.email
from email e
join email_relation r on (r.email_id = e.email_id and relation_type = "system")
where r.foreign_id = 1