bateman_ap
bateman_ap

Reputation: 1921

Selecting multiple values from linked table in MySQL using AND

Tech used: MySQL 5.1

I have a MySQL Query below:

SELECT 
  property.propertyId,
  categoryRelationships.categoryId
FROM
  property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
 categoryRelationships.categoryId IN (11,12)

This returns a result such as:

propertyId    categoryId
972           11
1071          11
1622          12
1622          11

However what I want to do is only return the propertyId's where it has both category 11 and 12 in it (in the case above 1622)

I have tried

SELECT 
  property.propertyId,
  categoryRelationships.categoryId
FROM
  property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
  categoryRelationships.categoryId = 11
  AND categoryRelationships.categoryId = 12

and

SELECT 
  property.propertyId,
  categoryRelationships.categoryId
FROM
  property
LEFT OUTER JOIN categoryRelationships ON (property.propertyId = categoryRelationships.propertyId)
WHERE
  categoryRelationships.categoryId IN (11)
  AND categoryRelationships.categoryId IN (12)

However this returns no results, it's driving me a little crazy how to do this.

A simple example of the two tables would be (I am returning a huge amount more info from the property table):

categoryRelationships

categoryRelationshipsId     categoryId      propertyId
2                           9               2136
3                           2               2136
4                           11              1622
5                           12              1622


property

propertyId                  propertyAddress
1622                        1 Anystreet
2136                        156 Stack Road

Upvotes: 1

Views: 400

Answers (1)

mechanical_meat
mechanical_meat

Reputation: 169344

This would seem to me to be the clearest, most-straighforward solution:

SELECT p.propertyaddress, t1.pid, t1.cid 
  FROM categoryRelationships t1
       LEFT JOIN property p ON p.property_id = t1.property_id
 WHERE EXISTS (
           SELECT 1 
             FROM categoryRelationships t2 
            WHERE t2.pid = t1.pid 
              AND t2.cid = 11) 
   AND EXISTS (
           SELECT 1 
             FROM categoryRelationships t3 
            WHERE t3.pid = t1.pid 
              AND t3.cid = 12);

Since sometimes MySQL isn't so adept at handling subqueries you could alternatively do something like this:

SELECT p.propertyaddress, t1.pid, t1.cid 
  FROM categoryRelationships t1 
       LEFT JOIN property p ON p.property_id = t1.property_id
       JOIN categoryRelationships t2 ON t2.pid = t1.pid 
   AND t2.cid = 11 
       JOIN categoryRelationships t3 ON t2.pid = t3.pid 
   AND t3.cid = 12;

Upvotes: 1

Related Questions