I’m currently running some SQL which uses an IN expression to match against multiple IDs. However, I would ideally like to be able to match up certain IDs with others so they must appear together to return a result. Here’s an example:
Edit: The IDs I’m matching are a part of a many-to-many relationship. The structure is like this:
Articles
ArticleKeywords
Keywords
An article can have multiple Keywords linked to it by the ArticleKeywords table. I am currently using the IN expression to match any of the Keyword IDs against the records. However, I’d like to match certain records against small groups of keywords i.e. a keyword must appear with another keyword for a record to be matched.
Current:
… AND id IN (’25’, ‘566’, ‘156’, ‘166’, ‘7345’)
More specific:
… AND ((id = ’25’ AND id = ‘566’) OR (id = ‘156’ AND id = ‘166’) OR (id = ‘7345’))
Although the second option might work, I’m thinking it probably won’t be very performance savvy. Is there another way this can be done, or should I be going about it another way?
Thanks for your help.
Edited based on comments. Say you’re searching for articles that:
You can query like:
Per SquareCog’s comment, you can greatly increase performance with an early WHERE clause. The clause would limit the grouping to the relevant keywords only. In the above query, add the WHERE just before the HAVING:
You can retrieve the other details of the article(s) like:
Say you have a table that contains groups to search for, defined like:
Meaning the article has to match ((keyword 1 and keyword2) or keyword3). Then you can query like this: