SELECT
SQL_CALC_FOUND_ROWS products.product_id,
descr1.product as product,
companies.company as company_name,
popularity.total as popularity,
MIN(
IF(
prices.percentage_discount = 0,
prices.price,
prices.price - (
prices.price * prices.percentage_discount
)/ 100
)
) as price,
absolute_rating.rating AS absolute_vendor_rating,
products.product_type,
products.parent_product_id,
products.list_price as list_price,
MAX(
100 - (
(prices.price * 100) / products.list_price
)
) AS sales_discount
FROM
cscart_products as products
LEFT JOIN cscart_product_features_values ON cscart_product_features_values.product_id = products.product_id
AND cscart_product_features_values.lang_code = 'en'
LEFT JOIN cscart_product_features ON cscart_product_features_values.feature_id = cscart_product_features.feature_id
LEFT JOIN cscart_product_descriptions as descr1 ON descr1.product_id = products.product_id
AND descr1.lang_code = 'en'
LEFT JOIN cscart_product_prices as prices ON prices.product_id = products.product_id
AND prices.lower_limit = 1
LEFT JOIN cscart_product_prices as prices_2 ON prices.product_id = prices_2.product_id
AND prices_2.lower_limit = 1
AND prices_2.price < prices.price
AND prices_2.usergroup_id IN (0, 0, 1)
LEFT JOIN cscart_companies AS companies ON companies.company_id = products.company_id
INNER JOIN cscart_products_categories as products_categories ON products_categories.product_id = products.product_id
INNER JOIN cscart_categories ON cscart_categories.category_id = products_categories.category_id
AND (
cscart_categories.usergroup_ids = ''
OR FIND_IN_SET(
0, cscart_categories.usergroup_ids
)
OR FIND_IN_SET(
1, cscart_categories.usergroup_ids
)
)
AND cscart_categories.status IN ('A', 'H')
AND cscart_categories.storefront_id IN (0, 1)
LEFT JOIN cscart_product_popularity as popularity ON popularity.product_id = products.product_id
LEFT JOIN cscart_absolute_rating AS absolute_rating ON absolute_rating.object_id = products.company_id
AND absolute_rating.object_type = 'company'
LEFT JOIN cscart_product_sales ON cscart_product_sales.product_id = products.product_id
AND cscart_product_sales.category_id = products_categories.category_id
WHERE
1
AND companies.status IN ('A')
AND (
products.usergroup_ids = ''
OR FIND_IN_SET(0, products.usergroup_ids)
OR FIND_IN_SET(1, products.usergroup_ids)
)
AND products.status IN ('A')
AND prices.usergroup_id IN (0, 0, 1)
AND prices_2.price IS NULL
AND products.parent_product_id = 0
AND products.company_id IN(NULL)
AND products.product_type != 'D'
GROUP BY
products.product_id
HAVING
sales_discount > 0
AND price < list_price
ORDER BY
sales_discount desc,
products.product_id ASC
LIMIT
0, 8