我想出了以下查询来返回产品定价数据。这个查询工作正常,但我想知道是否有办法简化/优化它?
该查询提取有关每种产品的产品和定价详情的信息。如果特定产品没有定价详细信息(p_p。pl_id
= 2),请加入另一个包含定价明细的查询(p_p。pl_id
= 1)。最后按id对所有产品进行分组以获得不同的行。
使用的表格: 产品 - 有关产品的一些详细信息,如名称,描述等。 product_pricing(p_p) - 包含每种产品的定价详情。一种产品的记录可能更多,因为产品价格根据订购数量而有所不同
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`
答案 0 :(得分:1)
编辑:我想我现在的意思是,试试:
SELECT t.col1, t.col2, --[more columns from products table]
IF (t.price2 IS NULL, t.price1, t.price2) AS price,
IF (t.price2 IS NULL, t.qty_range1, t.qty_range2) AS qty_range
FROM
(
SELECT p.col1, p.col2 , --[more columns from products table]
GROUP_CONCAT(p_p1.qty_range SEPARATOR '|') AS qty_range1,
GROUP_CONCAT(CAST(p_p1.p_price AS CHAR) SEPARATOR '|') AS price1,
GROUP_CONCAT(p_p2.qty_range SEPARATOR '|') AS qty_range2,
GROUP_CONCAT(CAST(p_p2.p_price AS CHAR) SEPARATOR '|') AS price2
FROM products p
LEFT JOIN prod_pricing AS p_p1 ON p_p1.prod_id = p.prod_id AND p_p1.pl_id = 1
LEFT JOIN prod_pricing AS p_p2 ON p_p2.prod_id = p.prod_id AND p_p2.`pl_id` = 2
GROUP BY p.prod_id) AS t
Having price IS NOT NULL
答案 1 :(得分:0)
由于两个UNIONS几乎相同,或许您可以查看CASE
你可以
WHERE `products`.`account_id` = 2
AND `products`.`prod_id`
AND CASE x
WHEN y THEN
p_p.`pl_id` = 2
ELSE
p_p.`pl_id` = 1
虽然目前尚不清楚您在何处/如何确定是否有定价细节。但是无论什么列确定 x ,它的值都在 y 中。
答案 2 :(得分:0)
好的,我终于明白了。 我创建了两个临时表t1,t2,它们反映了pl_id = 1和2的数据。接下来我将这些表连接到products表并使用IF条件返回产品,定价来自pl_id = 2和pl_id = 1仅当pl_id = 2的定价时不存在。 感谢大家的帮助!
这是查询
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