I have a many to many relationship between entries and keywords with a join table entries_keywords. I want to fetch all entries for both the keys ‘wake’ and ‘up’. The only way I came up with is this. If I want to throw in another search word it gets even worse. How do you refactor this? Is there another way to join it than using subqueries?
select *
from
(
select *
from entries e
inner join entries_keywords ek
on e.id = ek.entry_id
inner join keywords k
on ek.keyword_id = k.id
where k.key = 'wake'
) e
inner join entries_keywords ek
on e.id = ek.entry_id
inner join keywords k
on ek.keyword_id = k.id
where k.key = 'up';
If you only want to retrieve entries that have at least one of the keywords, you can do:
If you want to retrieve entries that have ALL of the keywords in the list, add
GROUP BYandHAVING:Where
2is the number of keywords in the list you’re checking on.