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.
There are many ways. This should be one:
SELECT badge_id
FROM ( -- count missions per badge for the given user
SELECT br.badge_id, count(*) AS ct
FROM finished_missions fm
JOIN badge_requirements br USING (mission_id)
WHERE fm.user_id = 221
GROUP BY 1
) u -- count missions per badge total
JOIN (
SELECT br.badge_id, count(*) AS ct
FROM badge_requirements
) b USING (badge_id, ct) -- only badges with the full count of missions
In addition to the constraints you declared there should also be a, UNIQUE(user, mission_id)
on finished_missions
to disallow duplicate entries. Or you have to use count(DISTINCT mission_id) AS ct
in the first subquery, so you can rely on the count.
And UNIQUE(mission_id, badge_id)
should really be the PK - or add a NOT NULL
constraint for both columns.