Tuesday, 13 August 2013

Find rows with multiple reference values in MySQL

Find rows with multiple reference values in MySQL

I've been struggling with this problem. Head against the wall. I know this
has to be easy.
I want to select items that match multiple criteria on a reference table.
Here is a example schema that can help illustrate the problem
tblCars
------------
CarID
CarName
tblCarColors
------------
ColorID
Color
tblCarColorXRef
------------
ID
CarID
ColorID
Basically, I want to find cars with multiple colors that I'm searching
against. To continue the example. Let's say Toyota in the car table is
multi-colored.. black and yellow
CarID of the Toyota would be 1
ColorID for black is 1 and yellow would be 2
I need to find all cars in the tblCarColorXRef table that match 1 AND 2.
Has to be 'and'. I don't want to find cars that are black or cars that are
yellow, but cars that contain both yellow and black.
The problem, is that I can search WHERE ColorID = 1 AND ColorID = 2. That
would never be true, so this is where the head banging starts. I need to
wrap this query with other criteria from other tables, I get close with
HAVING and COUNT but, that is not necessarily accurate or correct.
Side note... cars can have 1 or many colors with the XRef table.

No comments:

Post a Comment