- Anda dapat
GROUP BY
pada id dan nama pengguna. - Gunakan
HAVING
klausa denganSUM()
agregasi untuk menyaring kasus. - Jika pengguna tidak bekerja pada hari tertentu,
SUM()
untuk hari itu akan menjadi nol, posting bergabung.
Untuk kasus pertama (berfungsi tepat semua hari kerja dalam seminggu), Coba:
SELECT u.id, u.name
FROM USERS AS u
JOIN WORKDAYS AS wd ON wd.user_id = u.id
JOIN DAYS AS d ON d.id = wd.day_id
GROUP BY u.id, u.name
HAVING SUM(d.name = 'monday')
AND SUM(d.name = 'tuesday')
AND SUM(d.name = 'wednesday')
AND SUM(d.name = 'thursday')
AND SUM(d.name = 'friday')
AND SUM(d.name = 'sunday') = 0
AND SUM(d.name = 'saturday') = 0
Untuk kasus kedua, hapus saja ketentuan pada sunday
dan saturday
. Coba:
SELECT u.id, u.name
FROM USERS AS u
JOIN WORKDAYS AS wd ON wd.user_id = u.id
JOIN DAYS AS d ON d.id = wd.day_id
GROUP BY u.id, u.name
HAVING SUM(d.name = 'monday')
AND SUM(d.name = 'tuesday')
AND SUM(d.name = 'wednesday')
AND SUM(d.name = 'thursday')
AND SUM(d.name = 'friday')