mysql多个外键关联,MySQL多个外键

I'm new to setting up relational databases.

I'm trying to create two tables in MySQL, a USER table and a COMPANY table. Both should be able to have multiple phone numbers associated with them, so I created a PHONE table and wanted to have a one-to-many relationship from both COMPANY to PHONE, and from USER to PHONE.

There only seem to two options in what I am trying to do:

Keep two foreign keys in PHONE, one referencing COMPANY, and one referencing USER. They would both default to NULL and each and when creating a new row in PHONE, I would only fill the one that I need.

Have two different tables, USER_PHONE and COMPANY_PHONE.

Neither option seems optimal to me. Option 1 seems hacky and prone to redundancy issues. Option two seems pretty repetitive and unnecessary. I'm inclined to think that option 2 is the "official" way of doing things (starting to wonder if this is why I hear negative things about MySQL).

Anyone? Thanks,

-Matt

解决方案

I do like to suggest the following design(much like yours):

First of all, we will have three tables

USER -- UserId, other fields

COMPANY -- CompanyId, other fields

PHONE -- PhoneId, PhoneNumber

Then have two tables for storing the relation

COMPANY_PHONE -- CompanyId, PhoneId

USER_PHONE -- UserId, PhoneId

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值