简体   繁体   English

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

[英]Complicated SQL figuring out how to pull most recent data

I am writing a function to calculate an order total. 我正在写一个函数来计算订单总数。 I am looking at an SQL to pull this information and not hack it up with php like I currently have. 我正在查看一个SQL来提取此信息,而不是像现在一样使用php对其进行破解。

Each order has order offers for each item. 每个订单都有每个商品的订单报价。 Since we commonly have order amendments there might be more than one version of an order offer. 由于我们通常会有订单修订,因此订单报价可能有多个版本。 The highest offer version is the data we use in calculating a price. 最高报价版本是我们用于计算价格的数据。

Now, here is the SQL I use to pull all of the order offers for the individual orders: 现在,这是我用来提取单个订单的所有订单报价的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)

Now, I need to create a similar SQL to pull the coupons for each order offer. 现在,我需要创建一个类似的SQL来为每个订单商品提取优惠券。 Each order offer MAY have more than one coupon or may not have them at all. 每个订单报价可能有一个以上的优惠券,也可能根本没有。

Here is the SQL I use to find valid order offers that CAN have coupons applied (if it helps) 这是我用来查找可以应用优惠券的有效订单报价的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
)

Thank you for the help! 感谢您的帮助!

Can't you do just this (it will give you the coupons to the last offer): 您不能这样做吗(它将为您提供上次报价的优惠券):

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM