我有两个表连接,其中一个表包含产品数据,其他定价数据包括多个折扣定价。并非每个产品在定价表中都有多个条目,因为有些产品只有一个单价。 我想弄清楚的是在我的选择中如何设置一个标志,让我知道产品是否有多种定价。
我现在的代码(见下文)返回产品并找到每种产品的最低价格。但是我说并非所有产品都有“最低价”。我正在尝试确定产品的价格是单个单价还是最低价。
SELECT products.*
, products_pricing.*
FROM products
LEFT
JOIN products_pricing
ON products.product_id = products_pricing.product_id
LEFT
JOIN products_pricing AS filter
ON products_pricing.product_id = filter.product_id
AND products_pricing.qty_price > filter.qty_price
WHERE filter.product_id IS NULL
AND products.product_active > 0
ORDER
BY products.product_id DESC
答案 0 :(得分:0)
根据您的描述,我收集到每个产品至少有products_pricing
的价格,因此无需外部联接。
我只是加入聚合产品,而不是使用反连接模式。使用min / max或count的比较来获得你的旗帜。
select
p.*,
pp.*,
case when ppm.min_qty_price = ppm.max_qty_price then 'single' else 'multi' end as flag
from products p
join products_pricing pp on pp.product_id = p.product_id
join
(
select product_id, min(qty_price) as min_qty_price, max(qty_price) as max_qty_price
from products_pricing
group by product_id
) ppm on ppm.product_id = pp.product_id
and ppm.min_qty_price = pp.qty_price
where p.product_active > 0
order by p.product_id desc;
答案 1 :(得分:0)
如果您不需要两个表中的所有列,只需要相关的列
SELECT products.product_id, count(*) as num_of_price
, case when count(*) > 1 then 'MULTI PRICE' ELSE 'SINGLE PRICE' as flag_price
FROM products
LEFT
JOIN products_pricing
ON products.product_id = products_pricing.product_id
WHERE products.product_active > 0
GROUP BY products.product_id
ORDER
BY products.product_id DESC
如果您需要所有列,则可以加入此结果
SELECT products.*
, products_pricing.*
, t.*
FROM products
LEFT JOIN products_pricing ON products.product_id = products_pricing.product_id
LEFT JOIN (
SELECT products.product_id, count(*) as num_of_price
, case when count(*) > 1 then 'MULTI PRICE' ELSE 'SINGLE PRICE' as flag_price
FROM products
LEFT
JOIN products_pricing
ON products.product_id = products_pricing.product_id
WHERE products.product_active > 0
GROUP BY products.product_id
) T ON products.product_id = T.product_id
ORDER
BY products.product_id DESC