我正在研究自定义电子商务解决方案,但我不知道如何从2个不同表的2列中选择最低价格。
[DEBUG] [09/11/2018 09:53:43.328] [TestSystem-akka.actor.default-dispatcher-5] [akka://TestSystem/system/IO-TCP/selectors/$a/0] Connection established to [192.168.56.2:8563]
[DEBUG] [09/11/2018 09:53:43.346] [TestSystem-akka.actor.default-dispatcher-17] [akka.stream.Log(akka://TestSystem/system/StreamSupervisor-0)] [SendAnnounce] Upstream finished.
[DEBUG] [09/11/2018 09:53:43.346] [TestSystem-akka.actor.default-dispatcher-17] [akka.stream.Log(akka://TestSystem/system/StreamSupervisor-0)] [AnnouncementResponse] Upstream finished.
因此表shop_products具有许多shop_products_variants。您可以在shop_products表上指定price或price_sale,但也可以为自定义变量指定price或price_sale。 我需要为每个产品(包括产品变体)选择价格最低的产品。我可以找到不同价格的MIN价格,但无法将shop_products的MIN价格和shop_products_variants的MIN价格结合起来。
TABLE: shop_products
id
title
price
price_sale
TABLE: shop_products_variants
id
product_id
price
price_sale
我将不胜感激...
答案 0 :(得分:1)
您可以加入“ shop_product”表和“ shop_products_variants”表,之后在结果集中可以找到最低价格。例如:
SELECT sp.id,
sp.title,
MIN(LEAST( IFNULL(sp.price_sale, sp.price, sp.price_sale),
IFNULL(spv.price_sale, spv.price, spv.price_sale)
)) AS min_price
FROM shop_products AS sp
LEFT JOIN shop_products_variants AS spv ON shp.product_id = sp.id
GROUP BY sp.id,
sp.title
答案 1 :(得分:0)
对于products_variants中的price和price_sale为NULL的情况,Maxim的答案仅适用于较小的修正。
MIN(LEAST( IFNULL(shop_products.price_sale, shop_products.price),
IFNULL(
IFNULL(shop_products_variants.price_sale, shop_products_variants.price), shop_products.price)
)
) AS min_price