I have a MySQL table to store product variants option values (eg: colour, size, weight, the height of product variants). It contains the following data.
I have a filter option on the frontend, where users can select filter options such as colour, size, weight, height etc and I need to show product variants based on the filter values.
In the above example: option_id = 110 means size. option_id = 109 means color. Suppose a user-selected size = 31 (XL) and colour = 27 (Red),
I have to find a product_variant_id where option_id = '110' AND option_value_id = 31 AND option_id = '109' AND option_value_id = 27. (result should be records with ids 266 and 267)
There is only one such product_variant_id that is 140.
I tried
SELECT * FROM product_variant_option_values WHERE (option_id = '110' AND option_value_id = 31) OR (option_id = '109' AND option_value_id = 27)
but it's not returning what I want, the above query returns
OK, after seeing the result you are getting right now. If I understand correctly, you want product_variant_id
that has exactly the two conditions you mentioned. So one option for a query could be:
SELECT product_variant_id
FROM product_variant_option_values
WHERE (option_id = '110' AND option_value_id = 31) OR (option_id = '109' AND option_value_id = 27)
GROUP BY product_variant_id
HAVING count(*) = 2
Which means, that you count the number of rows returned per each product_variant_id
and only return the one that has 2 rows. Which means got the two conditions.
I think what you can do is to add a COUNT()
operation to see if both of the filter condition are met. Something like below:
SELECT product_variant_id,COUNT(*) cnt
FROM product_variant_option_values
WHERE (option_id = '110' AND option_value_id = 31)
OR (option_id = '109' AND option_value_id = 27)
GROUP BY product_variant_id
HAVING cnt >= 2;
Grouped by product_variant_id
whereby the result of COUNT()
is 2 or more; of if the filter condition is always going to be 2 then just HAVING cnt=2
should suffice. This query can similarly be written this way:
SELECT product_variant_id,COUNT(*) cnt
FROM product_variant_option_values
WHERE option_id in ('110','109')
AND option_value_id IN (27,31)
GROUP BY product_variant_id
HAVING cnt >= 2;
Fiddle example : https://www.db-fiddle.com/f/9kKmyHsSAMNk4BBPDWLHFh/3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.