Jan Cieslik
Jan Cieslik

Reputation: 67

MySQL: Select an item that matches multiple rows

I have a few (over 20) tables in MySQL, which describe an item on many different levels (colors, location etc.). The following is an example of "table01"

+----+----------+
| ID | property |
+----+----------+
|  1 | A        |
|  1 | B        |
|  2 | C        |
|  2 | B        |
+----+----------+

Now I want to search for items that match multiple criteria. The following query works just fine

SELECT
  table01.ID, table01.property, table02.property, table03.property [...]
FROM
  table01
LEFT JOIN table02 ON table02.ID = table01.ID
LEFT JOIN table03 ON table03.ID = table01.ID
[...]
WHERE
  table01.property = "A"
  and table02.property = "B"
  and table03.property = "A"
  [...]

Heres my problem. I want to search for an item that matches for a few properties in one table. For example (this query obviously does not work)

table01.property = "A" AND table01.property = "B"

I don't know how to achieve that, because the information is stored in multiple rows.

Any suggestions? The database is huge (a few thousand entries per table) and new rows get added from time to time. Should I do some of the processing through PHP or is there a pure MySQL Solution?

Upvotes: 0

Views: 125

Answers (2)

Harshil Doshi
Harshil Doshi

Reputation: 3592

You can use query given by @Gnudiff with your query as follows:

SELECT
  table01.ID, table01.property, table02.property, table03.property [...]
FROM
  (SELECT *FROM table01 
   WHERE property = 'A' OR  property = 'B'
   GROUP BY ID
   HAVING count(property)=2) as table01
LEFT JOIN table02 ON table02.ID = table01.ID
LEFT JOIN table03 ON table03.ID = table01.ID
[...]
WHERE
  table02.property = "B"
  and table03.property = "A"
  [...]

Click here for Demo

Hope it helps!

Upvotes: 0

Gnudiff
Gnudiff

Reputation: 4305

You could achieve this, for example, by doing

SELECT ID,count(property) AS CNT FROM table01 
WHERE property = 'A' OR  property = 'B'
GROUP BY ID
HAVING CNT=2;

This will give you list of IDs who have both properties.

However, it can grow more convoluted with more properties to check for AND unwieldy with more tables. If at all possible, it might be more useful to rethink your database schema to at least have a single table with properties, not multiple.

Upvotes: 2

Related Questions