Skip to content
Advertisement

How to check a value of a record referenced by foreign key in a constraint in MySQL

I am currently using MariaDB on arch and whatever is in debian buster reps as mysql in “production”.

I’m trying to create following schema:

The goal is to have a m:n relation with tags that have tag_meta column true and with any other tags (meta or not).

But I can’t find any resource on this since every time I try to google I see foreign key constraint everywhere.

I also tried to make a function but it says that function cannot be used in check clause. (error 1901)

Advertisement

Answer

Here’s a solution:

This uses a nonstandard feature of InnoDB, that it allows a foreign key to reference a non-unique index of the parent table. Normally this is something to avoid, because what does it mean for a child row to reference multiple parent rows? But in this case, since tags.tag_id is unique by itself, that won’t happen.

The way this works is that the pair of columns in tag_aliases must match the corresponding pair in tags. But we put a check constraint on tag_aliases.tag_meta that it must be true, therefore that foreign key can be satisfied only if it references a row in tags that has tag_meta = true.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement