MySQL在多表查询中检索最低价值

时间:2013-06-25 21:11:10

标签: mysql join

我的目标是检索已接受采购订单上商品的记录购买价格。

Purchase_Orders表包含订单的元数据,例如订单号及其状态(例如,1表示已接受,0表示已拒绝)。

Purchase_Ord_Contents表包含内容记录,这些记录通过外键链接到共享索引上的父采购订单order_number)

例如:我的数据库中有两个订单,一个已被接受,另一个已被拒绝。数据表示如下:

 =========================================
           PURCHASE_ORDERS TABLE
 =========================================
 id   |   order_number   |   order_status
 -----------------------------------------
  1          PO_100               0
  2          PO_101               1
  3          PO_102               1

===================================================
           PURCHASE_ORD_CONTENTS TABLE
===================================================
id    | order_number | purchase_price |    sku
---------------------------------------------------
   1       PO_100           1.50          APPLE
   2       PO_100           1.50          ORANGE
   3       PO_101           2.00          APPLE
   4       PO_101           2.00          ORANGE
   5       PO_102           1.75          BANANA

查询应该返回第3,4和5行,因为PO_101被接受了,而PO_100被拒绝了,第5行不仅是给定SKU的唯一记录,它也是接受订单。我尝试了一些不同的方法,但我似乎总是要么省略了未接受的采购订单上的部分,要么为最低的order_number检索错误的purchase_price

这是我到目前为止(不正常工作)

SELECT a.*
FROM   purchase_ord_contents AS a
       JOIN (SELECT sku,
                    MIN(purchase_price) AS min_price
             FROM   purchase_ord_contents
             GROUP  BY sku) AS b
         ON ( a.sku = b.sku
              AND a.purchase_price = b.min_price )
WHERE a.order_number
IN (
   SELECT order_number
   FROM purchase_orders
   WHERE order_status != 0
)

此查询成功返回purchase_ord_contents表中的记录,但是它忽略了purchase_price为0的采购订单中最低order_status的记录。

任何指导都会非常感激,我不太熟悉“高级”SQL查询,因为您现在可能已经确定了。感谢您的时间,请不要犹豫,询问我是否应该提供更多信息。

2 个答案:

答案 0 :(得分:1)

这可能就是你要找的东西:

SELECT sku, purchase_price, order_number
FROM (
    SELECT MIN(purchase_price) AS purchase_price, sku
    FROM purchase_ord_contents
    JOIN purchase_orders USING (order_number)
    WHERE purchase_orders.order_status = 1
    GROUP BY sku
) AS min_sku_price -- this is the lowest sale price for each SKU
JOIN purchase_ord_contents USING (sku, purchase_price) -- gets all orders having sold a SKU at its lowest price
JOIN purchase_orders USING (order_number)
WHERE purchase_orders.order_status = 1

请注意,如果此SKU的最低价格在多个订单中提供,则会为一个给定的SKU返回多行。

答案 1 :(得分:0)

如果我理解正确,我认为你想要这个:

SELECT po.order_number, poc.sku, min(poc.purchase_price)
FROM purchase_orders AS po
 JOIN purchase_ord_contents AS poc ON poc.order_number = po.order_number
 WHERE po.order_status != 0
 GROUP by po.order_number, poc.sku
 order by po.order_number, poc.sku