I'm trying to get filtered data from mysql db and i have problem with multiple join with count function.
Based on user action (price range slider; checked checkboxes) query should display different product and refresh filters via ajax (update products count that match current filter);
And here is my query to show filters and count them for beds in my store:
SELECT COUNT(id_product) as productMatched,
product_to_features.id_feature_value,
feature_value_langs.name,
feature_value_langs.id_feature_value,
products.active
FROM product_to_features
LEFT JOIN feature_value_langs
ON product_to_features.id_feature_value =
feature_value_langs.id_feature_value
LEFT JOIN products
ON product_to_features.id_product = products.id
WHERE id_feature = " . $row['idFeature'] . "
AND products.active = 1
GROUP BY product_to_features.id_feature_value
And result looks like:
Bed size: 80x200(3) 140x200(1) 160x200(2) 180x200(1)
Problem is that query counts products from whole page that have bed size feature) (we have different types of beds and it's check them all, not the current bed category). What I need it's IF in sql that allows me to check if product match multiple checked options IN CURRENT FURNITURE type.
Db what's contain features attached to product (for example 54 - bed size - value 15981 size: 80x200
SELECT * FROM `product_to_features` WHERE `id_feature` = 54
id id_feature id_product id_feature_value
1371279 54 33434 15981
1385494 54 23421 16011
1385600 54 23422 16012
1385653 54 23423 16013
1385706 54 23426 16012
And what data i need: - when user check bed size 80x200cm (query should take product with id_feature_value = 15981 - if user is in main beds category - query should also check for id_feature_value = 1483 (whitch mean - beds main category)
Of course if user choose more options query should use more sql IFs.
Thanks for any help!
Try changing COUNT(id_product)
to COUNT(DISTINCT id_product)
.
Is there some reason for LEFT
? Might the langs and products be missing even though the mapping table has a row?
See this for tips on many:many table design.
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.