Constraint for 2 foreign keys to have same secondary column value

All we need is an easy explanation of the problem, so here it is.

Suppose I have a table such as Users that has a id and a company_id
I want to make a 2nd table that has pairs of user id’s ex: (primary_key_id, user1_id, user2_id).

The user id’s must be in the same company for these pairs of users.

How can I add a constraint to my database to require this?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can create a unique constraint across company_id and id of the User table, then create two foreign keys that reference them.

Syntax for MySQL

  id int PRIMARY KEY,
  company_id int,
  UNIQUE KEY (company_id, id)

  company_id int,
  user1_id int,
  user2_id int,
  PRIMARY KEY (company_id, user1_id, user2_id),
  FOREIGN KEY (company_id, user1_id) REFERENCES `User` (company_id, id),
  FOREIGN KEY (company_id, user2_id) REFERENCES `User` (company_id, id)
INSERT `User` (id, company_id) VALUES
INSERT UserPair (company_id, user1_id, user2_id) VALUES(1,1,2);
INSERT UserPair (company_id, user1_id, user2_id) VALUES(1,1,3);
-- Cannot add or update a child row: a foreign key constraint fails

db<>fiddle (for SQL Server, which is slightly different syntax)

The constraint fails because there is only a single company_id which each foreign key uses, but one of the corresponding parent rows has a different company_id.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply