We are developing real estate software and with new version we are launching amenities search. That means that each property can have unlimited number of amenities and each search can be based on checked amenity (smoking allowed, pets, parking etc).

Tables important for this problem:

properties - id, title, description, price, ...

amenities - id, name

amenities_properties - amenity_id, property_id

Now, within a search there are checkboxes that are used to select amenities that must be present in a property. So we tried something like this:

This gets all properties that have at least one of the selected amenities, but we need only the properties that have them all! For example search is checked to search "smoking permitted" and "pets allowed". The result will show all the properties that have "smoking permitted" even with pets allowed option not checked.

However, this shows no results. What we need is to show results that have all properties that have all the parameters checked. I hope this makes sense

swampBoogie
—
2013-05-27T13:45:36Z —
#2

select properties.*
from properties
join amenities_properties
on properties.id = amenities_properties.property_id
where amenities_properties.amenity_id in (9,15,24)
group
by properties.id
having count(*) = 3

Webinsane
—
2013-05-27T15:29:35Z —
#3

Thanks a bunch Swamp.

This works nicely from phpMyAdmin, but we have no results in live search since we have large search query that is generated through ORM depending on checked options with more joined tables.

guido2004
—
2013-05-27T16:13:29Z —
#4

If you don't post the real query, it's hard to get a useful answer. I'd say swampBoogie's solution is the way to go, you'll just have to find a way to implement it in your extended query.

Webinsane
—
2013-05-29T09:00:19Z —
#5

With small modifications it is working without changing search query:

select properties.*
from properties
join amenities_properties
on properties.id = amenities_properties.property_id
where amenities_properties.amenity_id in (9,15,24)
group
by properties.id
having count(distinct amenities_properties.amenity_id) = 3

Thanks

guido2004
—
2013-05-29T10:03:30Z —
#6

Great

Webinsane
—
2013-05-30T17:24:33Z —
#7

All looking good, but now we have problem with pagination since no properties are shown on the next page.