The situation is quite similar to that shown in this question Select row from one table where multiple rows in another table have determined values, but the condition is more complex.
I have two tables in MySQL:
Products:
id | value
================
1 | foo
2 | bar
3 | foobar
4 | barbar
And properties:
product_id | property_id
=============================
1 | 10
1 | 11
2 | 15
2 | 16
3 | 10
3 | 11
3 | 12
4 | 10
4 | 16
5 | 16
6 | 11
I may have a filter that defines various number of properties to be selected, let’s say I am interested in 3 of them. So I need to choose products and order them according to the following conditions:
- at first products having all 3 properties,
- then products having 2 properties only (if not matched by the first condition)
- then products having only 1 property (if not matched by conditions 1 and 2)
Within each condition the items are ordered according to property_id in ascending order.
So if I want to pick products with property_id = 10 or property_id = 11 or property_id = 12, then my results should be the following:
- product_id=3 (it has properties 10, 11 and 12)
- product_id=1 (it has properties 10 and 11)
- product_id=4 (it has property 10)
- product_id=6 (it has property 11)
How this can be efficiently done by MySQL?
2
Answers
Given that
order
ing thecount
result is not possible in the same query, we can lazily wrap it in anotherselect
as thefrom
reference.The query will return:
Keep in mind product with
id
6 won’t appear as it doesn’t exists in theproducts
table.Fiddle: https://www.db-fiddle.com/f/g1iZeMRQo95KvVLcZrFedd/0
It might be better for readability by using CTE, but I digress..
Try this:
Note: This is assuming the
properties
table does not have duplicate rows. If it does,we will need to use the derived table(select distinct * from properties) as tb
instead of base table for the FROM clause.