Here is my case:
TABLE 1: Tickets
Columns (id, user_id)
TABLE 2: Ticket Choices
Columns (id, ticket_id, choice_code)
So a user can't have a tickets with similar choices, e.g
TICKETS:
| id | user_id |
|---|---|
| 1 | john |
| 2 | mary |
Ticket Choices:
| id | ticket_id | choice_code |
|---|---|---|
| 1 | 1 | abc |
| 2 | 1 | xyz |
Would be allowed, but repeating the same entries for the same user/ticket owner should be considered invalid. But if the entries belong to a ticket that belongs to a different user, they should be accepted.
I have been able to do this on an application level with some validation, by querying the db first, then checking submitted data against the results.
Now, I want this to be enforced on the database level. I have read about check constraints but from my findings, when multiple tables/joins are to be used, they don't apply. Can something like this be enforced?
EDIT: More examples
Tickets:
- PK: 100, user: John
- PK: 102, user: John
- PK: 103, user: Mary
Ticket Choices.
PK: 200, Ticket FK: 100, Choice Code: ABC
PK: 201, Ticket FK: 100, Choice Code: JFK
PK: 202, Ticket FK: 102, Choice Code: ABC
PK: 203, Ticket FK: 103, Choice Code: ABC
PK: 204, Ticket FK: 103, Choice Code: JFK
The following entries/should not be accepted once the above entries have been commited:
Ticket:
- PK: 104, user: John
- PK: 105, user: Mary
Ticket Choices.
PK: 205, Ticket FK: 104, Choice Code: ABC // Because a ticket choices set for John with {ABC} already exists
PK: 206, Ticket FK: 105, Choice Code: ABC
PK: 207, Ticket FK: 105, Choice Code: JFK
The last two because User Mary has a ticket with choice set {ABC, JFK} already.