简体   繁体   English

SQL外键基于指定表的列

[英]SQL Foreign Key based on column that specifies table

Suppose I have a table that contains a list of ids pointing to table names, with the following schema: 假设我有一个表,其中包含指向表名的ID列表,并具有以下架构:

RemoteTables
============
id (Primary Key)
tableName (string)

Suppose I also have the following schema in another table: 假设我在另一个表中也具有以下架构:

AnotherTable
============
id (Primary Key)
remoteTableId (foreign key referencing RemoteTables)
remoteId ("special" foreign key)

where remoteId points to a row in the table specified by remoteTableId . 其中remoteId指向remoteTableId指定的表中的remoteTableId

I have seen a few situations where I wanted to do this, but is there any built-in SQL support to manage the relationship in any way? 我已经看到了几种我想这样做的情况,但是是否有内置的SQL支持以任何方式管理这种关系?

What you have is a special type of constraint here, because you are building a custom meta-database (data dictionary of sorts). 在这里,您拥有的是一种特殊的约束类型,因为您正在构建自定义的元数据库(各种数据字典)。 So nothing "built in", per se. 因此,本质上没有“内置”的东西。

Your best bet would be to enforce this through a trigger, although triggers on MySQL unfortunately are not always as easy as they ought to be. 最好的选择是通过触发器来强制执行此操作,尽管不幸的是,MySQL上的触发器并不总是像应有的那样容易。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM