Here is the general setup.
I have the tables Cards, Attributes, and a join table between them. (Let’s call it Tags. It contains a CardID and an AttributeID.) The Attributes table is mostly just descriptions such as HasPower, IsPoisonous, ImmuneToWater, etc.
How would I go about querying for all cards that are both IsPoisonous and IsElectric? Let’s assume I have the IDs for those already (13 and 45), so technically, the Attributes table does not need to be part of this SQL. I concocted something like this, but I’m not even sure if it is optimal.
SELECT *, (COUNT * FROM Tags t WHERE t.CardID = c.CardID AND t.AttributeID IN (13, 45)) AS TagCount
FROM Cards c
WHERE TagCount = 2
I hope my question makes sense. Basically, imagine you are looking at a web UI; you are sifting through a pool of ~5000 cards and want to filter down your results. So, you start checking boxes: “Poisonous”, “Electric”, “Immune to Water”, etc. The results then filter down based on those attributes.
Thoughts?
Inner query fetches the CardIDs that have at least two of the attributes you’d specified, then uses that result as a filter to fetch the actual card data in the outer query.