4

Consider the following table structure:

UserGroup(ie. 'Admin')
    ID = 'Admin'
    ApplicationFK = 'App1'

JoinTable
    UserGroupFK = 'Admin'
    PermissionFK = 'Approve'
    PermissionValue = 'READ'

Permission(ie. 'Approve')
    ID = 'Approve'
    ApplicationFK = 'App2'

UserPermission
    UserFK = 'John'
    PermissionFK = 'Approve'
    PermissionValue = 'WRITE'

User
    ID = 'John'

Where you have a jointable between UserGroup and Permission, with both UserGroup and Permission having foreign keys to Application.

Is there any way to enforce integrity, to avoid the situation above, where the ApplicationFKs don't match? I cannot simply remove one of the Foreign Keys, as it is possible to have a Permission without any UserGroups, and possible to have a UserGroup without any permissions.

Sarov
  • 281
  • 2
  • 11

2 Answers2

1

Making sure I understand/have correctly elaborated on @ypercubeᵀᴹ's comment/linked answer:

The correct structure should be:

UserGroup(ie. 'Admin')
    ID = 'Admin'
    ApplicationFK = 'App1'
    [PK: ID, ApplicationFK]

JoinTable
    UserGroupFK = 'Admin'
    ApplicationFK = 'App1'
    PermissionFK = 'Approve'
    PermissionValue = 'READ'
    [PK: UserGroupFK, ApplicationFK, PermissionFK]
    [FK -> UserGroupFK+ApplicationFK -> UserGroup]
    [FK -> PermissionFK+ApplicationFK -> Permission]

Permission(ie. 'Approve')
    ID = 'Approve'
    ApplicationFK = 'App1'
    [PK: ID, ApplicationFK]

UserPermission
    UserFK = 'John'
    PermissionFK = 'Approve'
    ApplicationFK = 'App1'
    PermissionValue = 'WRITE'
    [FK -> PermissionFK+ApplicationFK -> Permission]

User
    ID = 'John'
Sarov
  • 281
  • 2
  • 11
0

The question will be solved after you define primary keys correctly.

Please remember that FK must point to other table's primary key (or unique key).

It is legal (at least in SQL) to use multi-field FKs.

filiprem
  • 6,747
  • 1
  • 19
  • 32