I came up with the following query to return product pricing data. This query works fine, although I’m wondering if there is a way to simplify/optimize it?
The query pulls info about the product and pricing details for each product. If there is no pricing details (p_p.pl_id = 2) for particular product join another query with pricing details (p_p.pl_id = 1). Finally group all products by id to get distinct rows.
Tables used:
products – some details about the products like name, description etc.
product_pricing (p_p) – contains pricing details for every product. There may be more that one records for one product because product price varies depending on ordered quantity
SELECT * FROM (
(
SELECT `products`.*,
GROUP_CONCAT(p_p.`qty_range` SEPARATOR '|') AS qty_range,
GROUP_CONCAT(CAST(p_p.`p_price` AS CHAR) SEPARATOR '|') AS price
FROM `products`
LEFT JOIN `prod_pricing` AS p_p ON p_p.`prod_id` = `products`.`prod_id`
WHERE `products`.`account_id` = 2
AND p_p.`pl_id` = 2
GROUP BY `products`.`prod_id`
)
UNION
(
SELECT `products`.*,
GROUP_CONCAT(p_p.`qty_range` SEPARATOR '|') AS qty_range,
GROUP_CONCAT(CAST(p_p.`p_price` AS CHAR) SEPARATOR '|') AS price
FROM `products`
LEFT JOIN `prod_pricing` AS p_p ON p_p.`prod_id` = `products`.`prod_id`
WHERE `products`.`account_id` = 2
AND p_p.`pl_id` = 1
GROUP BY `products`.`prod_id`
)) AS list
GROUP BY list.`prod_id`
Ok, I finally figured it out.
I created two temporary tables t1,t2 that reflect data with pl_id = 1 and 2. Next I joined those tables to the products table and with IF condition returned products with pricing from pl_id = 2 and pl_id =1 only when pricing for pl_id = 2 doesn’t exist.
Thanks to everyone for help!
Here’s the query
SELECT p.*, IF(t2.pl_id IS NULL,t1.qty_range,t2.qty_range) AS qty_range, IF(t2.pl_id IS NULL,t1.price,t2.price) AS price FROM products AS p LEFT JOIN ( SELECT p_p.prod_id, GROUP_CONCAT(p_p.qty_range SEPARATOR '|') AS qty_range, GROUP_CONCAT(CAST(p_p.p_price AS CHAR) SEPARATOR '|') AS price FROM prod_pricing AS p_p WHERE p_p.pl_id = 1 GROUP BY p_p.prod_id ) AS t1 ON t1.prod_id = p.prod_id LEFT JOIN ( SELECT p_p.prod_id,p_p.pl_id, GROUP_CONCAT(p_p.qty_range SEPARATOR '|') AS qty_range, GROUP_CONCAT(CAST(p_p.p_price AS CHAR) SEPARATOR '|') AS price FROM prod_pricing AS p_p WHERE p_p.pl_id = 1 GROUP BY p_p.prod_id ) AS t2 ON t2.prod_id = p.prod_id WHERE p.account_id = 2