Question

I have a table "comments", containing a basic auto-inc PK "id" field, and also a "type" field. At another tables, I want to have referential integrity applying a CONSTRAINT to comments.id AND ALSO the "type", using a fixed value for the type value.

Example: at table "question_comments_rate", I want to enforce "comment_id" to exist as field "id" in "comments" table [this is the easy part] AND ALSO that the "type" column is equal to "question".

Does this exist? How can I write this constraint declaration?

It is like a "conditional constraint" - not only "comment_id" field must exist as "comments.id", but also this "id" at "comments" table needs to be of a row where "type" is equal to "question" (or other specified value)...

I hope the problem is clear. I may make it clearer with your help/feedback. Thanks.

Was it helpful?

Solution

This would be a CHECK constraint, about which the MySQL manual says:

The CHECK clause is parsed but ignored by all storage engines.

You could instead create triggers on insert/update to enforce your sanity checks.

Or, in your case, you could make the data type of your type column ENUM('question') so that it cannot take any other value (except '', which all ENUM types can be - for example if they are set to an invalid value).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top