Mysql – complex thesql constraints over foreign keys

constraintMySQL

It seems rational to me to stop users or bad codes from inserting invalid data, but I don't remember to see this anywhere!

Consider the following tables
enter image description here

  • How I can make sure an order is always referencing an address that is created by the same user?
  • Is this kind of constraint usual and recommended? I mean, Do I even have to care about it in the design?

Best Answer

ALTER TABLE orders
  ADD FOREIGN KEY (user_id, address_id)
      REFERENCES address (user_id, id);

A single row then cannot have a user_id and address_id that do not appear on a row together in the address table.

Yes, I would say you want such a constraint.