I’ve got a query that i’d like to optimize. I’m certain that this query can be improved.
The result of the query should return the number of products that have the filter_id 22 and 2 and have display ‘yes’.
SELECT COUNT(product_id) AS Total
FROM kkx_filters_products
LEFT JOIN kkx_products ON product_id = kkx_products.id
WHERE filter_id IN (2,22)
AND kkx_products.display = 'yes'
GROUP BY product_id
HAVING count(product_id) = 2
The above query returns 10230 records each with the field Total and value 2.
I’d like one result with the field Total and value 10230.
I’ve included the structure of the tables being used in the query.
EXPLAIN kkx_filters;
Field Type Null Key Default Extra
id int(11) unsigned NO PRI NULL auto_increment
name varchar(50) NO
EXPLAIN kkx_filters_products;
Field Type Null Key Default Extra
filter_id int(11) NO PRI 0
product_id int(11) NO PRI 0
EXPLAIN kkx_products;
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
title varchar(255) NO
display enum('yes','no') NO yes
You could wrap your query with:
but it won’t be very efficient. Instead, join the products table to the filter table, twice: