Suppose I have four tables: USER, ORGANIZATION, TEAM, and TEAM_MEMBER.
Table ORGANIZATION
ID Name
1 Foo
2 Bar
Table USER
ID Name OrgID
1 John 1
Table TEAM
ID Name OrgID
1 Blue 1
2 Red 2
Table TEAM_MEMBER
ID UserID TeamID
1 1 1
A USER and TEAM both belong to an organization directly via a FK. And a USER belongs to one or more teams via an entry in TEAM_MEMBER, which contains a FK to both a USER and a TEAM.
In the example above, I would like to prevent the case where we try to create a row in TEAM_MEMBER for user John and team Red. John belongs to org Foo, and Red is a team in org Bar, so it would nonsensical to have a user assigned to a team in the wrong org.
How can I get the DB to prevent such a scenario? Is there a CHECK constraint or a trigger that can fail if TEAM_MEMBER->USER->OrgID and TEAM_MEMBER->TEAM->OrgID don't match?