我有一个两个表连接,其中一个表保存产品数据,另一个表保存包括多个折扣定价的定价数据。并非每种产品在定价表中都有多个条目,因为某些产品只有一个单价。 我想要弄清楚的是,在我的选择中如何设置一个标志,让我知道产品是否有多种可用定价。
我现在拥有的代码(见下文)返回产品并找到每种产品的最低价格。然而,正如我所说,并非所有产品都有“最低价格”。我正在尝试确定产品附带的价格是单个单价还是最低价格。
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
最佳答案
根据您的描述,我了解到每种产品在 products_pricing
中至少有一个价格,因此不需要外部联接。
我不会使用反连接模式,而是简单地使用聚合产品进行连接。然后使用最小/最大的比较或计数来获得您的标志。
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;
关于mysql join 选择最低价格设置标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40721120/