Hello. This question is somewhat similar to blackhorse's thread from today, but I didn't want to break into his thread.
I have 2 tables: products and products_categories_xref
As you can see, the second one stores crossreference between products and their categories. There are 3 levels of categories. Categories ids are uniqe integers (independent of their level).
What I want to do is to search for products with some conditions that belong to either main category c1, subcategory c2 or second-level subcategory c3 and sort the list in this order:
- order of relevance - first products found for category c3 then c2 and last c1
- specified order inside category
Thus far I have come up with this:
The easiest way would be to
SELECT DISTINCT products.id, list_of_other_fields
FROM products, products_categories_xref
WHERE products.id = products_categories_xref.category_id
AND (products_categories_xref.category_id = 'c3'
OR products_categories_xref.category_id = 'c2'
OR products_categories_xref.category_id = 'c1')
AND whatever conditions here
ORDER BY products_categories_xref.category_id, whatever order inside category
LIMIT start, offset
But then categories ids aren't sorted in this way that c1, c2, c3 are in some order - c2 can be greater then c1 but c3 can be the lowest.
Another solution:
(SELECT DISTINCT products.id, list_of_other_fields
FROM products, products_categories_xref
WHERE products.id = products_categories_xref.category_id
AND products_categories_xref.category_id = 'c3'
AND whatever conditions here
ORDER BY whatever order inside category)
UNION
(SELECT DISTINCT products.id, list_of_other_fields
FROM products, products_categories_xref
WHERE products.id = products_categories_xref.category_id
AND products_categories_xref.category_id = 'c2'
AND whatever conditions here
ORDER BY whatever order inside category)
UNION
(SELECT DISTINCT products.id, list_of_other_fields
FROM products, products_categories_xref
WHERE products.id = products_categories_xref.category_id
AND products_categories_xref.category_id = 'c1'
AND whatever conditions here
ORDER BY whatever order inside category)
LIMIT start, offset
This has disadvantage as well - product can belong to category c1 as well as c2 as well as c3 (in most cases it will). So no advantage of distinct record (that's what I do right now - use this query and eliminate doubles inside php). But start and offset are useless here.
Anyone has better ideas on how to achieve this? can you say to mysql "order by c3 first c2 second c1 third, regardless of c1, c2, c3 values"?