mysql引用其他表主键,MySQL外键使用多个字段来引用另一个表中的主键

I want to reference 2 of my columns in one table to a primary key from another table. Here is how it looks like in the db structure:

Users

uid (INT) name (VARCHAR)

1 John Doe

2 Jane Doe

SystemProcesses

uid (INT) name (VARCHAR)

1 Hitman

2 Cron

Logs

uid (INT) modelType (VARCHAR) modelUID (INT) Action

1 Users 2 Jane Doe did this

2 Users 1 John Doe did that

3 SystemProcesses 1 Hitman just killed John Doe

How do I reference modelType and modelUID in Logs table to those Users and SystemProcesses?

If it's not possible, what is the the alternative?

解决方案

Don't use the same column for both foreign keys. This is sometimes called polymorphic associations, and it breaks rules of good database design.

It should be a clue that it's a bad design, that a FOREIGN KEY constraint supports only one referenced table. There is no support for polymorphic associations in standard SQL.

Instead, create two columns, one for a reference to Users, the other for a reference to SystemProcesses. One column per referenced table.

Logs

uid (INT) UsersID (INT) SystemProcessesID (INT) Action

1 2 NULL Jane Doe did this

2 1 NULL John Doe did that

3 1 1 Hitman just killed John Doe

If there is no relevant reference for either the Users or SystemProcesses column, use NULL to indicate there's no applicable value.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值