I have the next layout of tables:
table COMPANY:
- primary key pk_company
table USERS:
- primary key pk_users,
- foreign key (fk_company) references COMPANY (pk_company)
table GROUPS: <br>
- primary key pk_group,
- foreign key (fk_company) references COMPANY (pk_company)
table ROLES:
- primary key pk_role
table RELATIO_UGR:
- foreign key (fk_user) references USERS (pk_user)
- foreign key (fk_group) references GROUPS (pk_group)
- foreign key (fk_role) references ROLES (pk_role)
- Also: UNIQUE KEY [fk_user,fk_group]
This is:
USER ---(n:m)--- GROUP ---(m:1)--- COMPANY
USER ------------(n:1)------------ COMPANY
1 company can have N users (workers)
1 company can have M groups
M groups can have N users (each worker can be in more than one group)
1 user can have only 1 role (read / read-write / admin) in each group.
The thing is that all constraints seem to work in the individual tables, however, the RELATIO_UGR
table fails to establish constraints.
Let's suppose we have:
- USER1 from GROUP1 and COMPANY1
- USER2 from GROUP2 and COMPANY2
The RELATIO_UGR
shouldn't allow me to establish (for example) the relationship:
USER2-GROUP1-COMPANY2
Yet, I CAN insert
it...
How do I restrict it?
pk_company
in therelatio_ugr
table and adjust foreign keys accordingly (and add unique keys inusers
andgroups
).unique (user, group)
is for the "1 user can have only 1 role (read / read-write / admin) in each group" constraint. This should be kept, it's not related to the issue.