我有一个ProductTable和SalesTable。
产品表包含我所有的产品,所有产品都有唯一的ID,但有时会重复MPN(项目产品代码)。我对每种特定mpn的最低价商品感兴趣,这很简单。下面的查询为product表解决了此问题。
select model, min(price) price, quantity from tcart_product where quantity > 0 group by model
足够简单...
但有时某些商品会出售。这些销售记录在销售表中,有效销售记录了相应的产品编号(无mpn)。 因此,某商品的价格可能比mpn最低价的商品要高,但是如果进行销售,则该商品将因销售而成为最低价的商品。
因此,我需要选择价格最低的商品的产品ID,但是如果有销售,我需要选择该商品。
我无法正常工作。
下面是我所拥有的。
select case when MIN(g.price)> s.SalePrice then s.salepid
else g.product_id
/*it's up to chance which product id gets selected. not necessarily lowest priced*/
end as saleproduct_id,g.mpn,
s.SalePrice from tcart_product g
left join
(SELECT product_id as salepid, price as SalePrice FROM tcart_product_special where date_end> curdate()) s
on g.product_id=s.salepid
where quantity > 0 group by g.model