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
This would seem to me to be the clearest, most-straighforward solution:
Since sometimes MySQL isn’t so adept at handling subqueries you could alternatively do something like this: