简体   繁体   中英

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:

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 .

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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