I got three tables.
I want to query the badges table to get the badge if all the missions exists for the badge_id
in the badge_requirements
table.
In the case below, the badge would be returned because for badge_id = 1
, all missions exist.
But if, for example, one record in the finished_missions
table would not exist, then no badge would be returned.
The user_id
will be supplied from the application.
table badges
+----+------+-------+
| id | name | image |
+----+------+-------+
| 1 | OHYE | path |
+----+------+-------+
PK(id)
table badge_requirements
+------------+----------+
| mission_id | badge_id |
+------------+----------+
| 3 | 1 |
+------------+----------+
| 5 | 1 |
+------------+----------+
UNIQUE(mission_id, badge_id)
FK(mission_id, missions.id)
FK(badge_id, badges.id)
table finished_missions
+----+---------+------------+
| id | user_id | mission_id |
+----+---------+------------+
| 3 | 221 | 3 | // if any of these record doesn't exist
+----+---------+------------+
| 5 | 221 | 5 | // the badge associated with this mission would not be returned
+----+---------+------------+
PK(id)
FK(user_id, users.id)
FK(mission_id, missions.id)
EDIT
Changed the missions
table to finished_missions
for better readability.
The user id and mission id are just referencing the user and mission table.
EDIT 2 I've tried this, given from an answer:
SELECT * FROM badges b
INNER JOIN finished_missions fm ON (fm.user_id = 221)
INNER JOIN badge_requirements br ON (br.mission_id = fm.mission_id AND br.badge_id = b.id)
But it still returns the badge even if I have just one record in finished_missions
table.