0

Thanks for reading this.

I have tables like this in MySQL:

enter image description here

Device table has a list of name. And ReservedName table has a list of "reserved" name list.

As you may see, my design concept is to make Name value of Device table SHOULD NOT one of Name in ReservedName.

I could easily implement this relation by add a few SQL statement when I do INSERT operation to Device table. But I am wondering if there is something like "Not one of" constraint in the table schema? Maybe opposite meaning of FOREIGN KEY? It is also welcome if there is any other way to make that relationship.

sstan
  • 35,425
  • 6
  • 48
  • 66
Bumsik Kim
  • 5,853
  • 3
  • 23
  • 39
  • you're looking for a check constraint. http://stackoverflow.com/questions/13000698/sub-queries-in-check-constraint may be useful – Kritner Aug 24 '16 at 15:29

1 Answers1

0

You can create a BEFORE INSERT triggers which can either cause an error or set the field to its default value when the requirements of the data are not met.

In your case you can create a trigger, which will raise error, if your validation fails, something like following:

CREATE TRIGGER `validate_before_insert` BEFORE INSERT ON `Device`
FOR EACH ROW
BEGIN
    IF EXISTS (SELECT* FROM ReservedName WHERE Name = new.Name) THEN
        SIGNAL SQLSTATE '12345'
            SET MESSAGE_TEXT := 'check constraint on Device.Name failed';
    END IF;
END

You can read more about MySQL triggeres in documentation.

Saurabh
  • 71,488
  • 40
  • 181
  • 244