问题
Quick question about the most efficient was to handle this, I have a database which has a tree structure of user types,
system --- 1 to m --- account --- 1 to m --- customer
All three types can have multiple email addresses, I was wondering what would be the best way to handle this in a database, all user types have auto_id as their primary key so having a table with address identified by there related primary key wont work as there will be potentially 3 of each. e.g. email with key 2 , will link to system with id 2 , account with id 2 , etc.
Should I create a table of email addresses for each type .? Or is there a more elegant solution .?
Thanks
回答1:
You either have an email table that has a foreign key which is either a system_id, account_id, or customer_id. Then you can have a field specifying the type of that foreign key. Another more complicated strategy would be to have still the email table but no foreign key. Another table which you would call email_relation consisting of the email_id and the foreign key. That way you could use one e-mail address for all three tables.
Example of the use of two tables
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
if you want the customer table including the e-mail address
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
If you want all e-mail to a system you could also
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
回答2:
You could construct a composite key to identify a record at any level of the hierarchy, then use it as a FK in your email table. So one email record could point to sys1.acc7
, some others could point to sys3.acc4.cus99
. The composite key is made up of auto_ids strung together in whatever way makes sense for your system.
You can determine this composite key for any point in the hierarchy, and from there find all the corresponding email addresses for that point.
来源:https://stackoverflow.com/questions/12226260/store-multiple-email-addresses-in-database-for-different-user-types