有可能有一个动态的外键,最好/正确的是什么? [英] Is it possible to have an dynamic foreign key, and what is the best/correct to do so?

查看:129
本文介绍了有可能有一个动态的外键,最好/正确的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:
我有一个带有外键的历史记录表,可以根据字段值指向不同的表/实体。

For example: I have a "history" table with a foreign key that might point to different tables/entities depending a field value.

表历史:

create table history(
    id int PimaryKey AUTO_INC,
    elementid int, (ForeignKey)
    elementtype varchar
)

此表填充例如:

id               ElementId           ElementType
1                1                   Device
2                2                   Simcard
3                2                   Simcard

这告诉我们有


  • 1具有id为1的Device类型的实体的记录

  • ID为2的Simcard类型的实体的2个记录

目标是拥有可能用于多个实体的表。

the goal is to have a table that might be used for multiple entities.

这是将动态集成的正确方法外键?
我还想到的是使用表/实体创建一个列表来引用
所以表格将如下所示:

Is this the correct way to integrate an dynamic foreign key? What I also thought of was for creating an list with tables/entities to refer to So the table then would look like:

ALTER TABLE history MODIFY ElementType INTEGER;

ElementType将引用:

ElementType would refer to:

create table entities(
    id int PimaryKey AUTO_INC,
    name varchar
)

填写新的表历史记录,例如:

the new table history is populated for example:

id               ElementId           ElementType
1                1                   1
2                2                   2
3                2                   2

例如:

id               name
1                Device
2                Simcard


推荐答案

实现动态FK的正确方法是不做。

The proper way to implement dynamic FKs is to not do it.

这是一个原因,以及代替

这篇关于有可能有一个动态的外键,最好/正确的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆