复杂的SQL弄清楚如何提取最新数据

时间:2013-05-09 23:24:17

标签: php mysql sql

我正在编写一个计算订单总额的函数。我正在寻找一个SQL来提取这些信息,而不是像我现在那样用PHP来破解它。

每个订单都有每个商品的订单优惠。由于我们通常会对订单进行修改,因此订单要约可能会有多个版本。最高报价版本是我们用于计算价格的数据。

现在,这是我用来提取各个订单的所有订单商品的SQL:

SELECT * FROM order_offer offer 
WHERE offer.order_id = ?
AND offer.offer_version IN (SELECT MAX(offer_version) FROM order_offer WHERE offer_id =     
offer.offer_id)

现在,我需要创建一个类似的SQL来为每个订单提供优惠券。每份订单可能会有多张优惠券或根本没有优惠券。

这是我用来查找可以应用优惠券的有效订单商品的SQL(如果它有帮助)

SELECT * FROM order_offer offer 
WHERE offer.order_id = ?
AND offer.offer_version IN (SELECT MAX(offer_version) FROM order_offer WHERE offer_id = 
offer.offer_id)
AND offer.offer_id NOT IN
(
SELECT o.offer_id
FROM order_offer o LEFT JOIN order_coupons c ON o.offer_id = c.offer_id 
WHERE o.offer_version = offer.offer_version
AND o.offer_version = c.offer_version
AND c.order_coupon_stackable = 0
AND o.order_id = offer.order_id
)

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你不能这样做(它会给你最后一个优惠的优惠券):

SELECT * FROM order_offer offer 
LEFT JOIN order_coupons c ON offer.offer_id = c.offer_id AND offer.offer_version = c.offer_version
WHERE offer.order_id = ?
AND offer.offer_version IN (SELECT MAX(offer_version) FROM order_offer WHERE offer_id =     
offer.offer_id)