Thursday, 29 August 2013

MySQL order by points from 2nd table

MySQL order by points from 2nd table

So I have MySQL 3 tables, items (which in this case are lodging properties
and the data is simplified below), amenities that the properties might
offer, and amenities_index which is a list of item ids and amenity ids for
each amenity offered. The end user can select any number of amenities they
want and I want to return the results in order of the number of amenities
that match what they are looking for. So, if they search for 3 different
amenities, I want the items listed that offer all 3, then those that offer
2, 1 and finally the rest of the items. I have a query that I think is
working for getting the results in the correct order, but I was hoping
that I could also return a point value based on the matches, and that's
where I'm running into trouble. My SQL skills are a bit lacking when it
comes to more complex queries.
Here is an example query I have that returns the results in the correct
order:
SELECT *
FROM items
ORDER BY (SELECT count(*) AS points
FROM `amenities_index`
WHERE (amenity_id = 1 || amenity_id = 2) AND
amenities_index.item_id = items.id
) DESC
And here is what the tables are structured like. Any help is appreciated.
items table:
id name
1 location 1
2 location 2
3 location 3
4 location 4
amenities table:
id name
1 fireplace
2 television
3 handicapped accessible
4 kitchenette
5 phone
amenities_index
item_id amenity_id
1 2
1 3
1 5
2 1
2 2
2 6
3 2
3 3
3 4
3 5

No comments:

Post a Comment