查找产品的最新货件(sql subselect?)

时间:2010-03-11 08:11:50

标签: sql mysql subquery

我有三张桌子

shipment (shipment_id, shipping_date)
company_order (company_order_id, shipment_id, company_id)
company_order_item (company_order_item_id, company_order_id, product_id)

几家公司聚在一起,汇总了一家制造商的订单。此汇总订单称为“货件”。公司在每批货物中订购一系列产品:因此,并非所有产品都会出现在任何一件货物或任何一家公司中。

如何编写SQL查询,查找每个product_id的最新货件?

我看过了 SQL Query - Get Most Recent Revision(更简单的情况)。

2 个答案:

答案 0 :(得分:1)

您需要获取每个产品ID的最大发货日期,然后检索发货详细信息

这样的东西
SELECT  *
FROM    (
            SELECT  coi.product_id,
                    MAX(s.shipping_date) MaxDate
            FROM    company_order_item coi INNER JOIN
                    company_order co ON coi.company_order_id = co.company_order_id INNER JOIN
                    shipment s ON co.shipment_id =s.shipment_id
            GROUP BY coi.product_id
        ) sub INNER JOIN
        company_order_item coi ON sub.product_id = coi.product_id INNER JOIN
        company_order co ON coi.company_order_id = co.company_order_id INNER JOIN
        shipment s ON   co.shipment_id = s.shipment_id
                    AND s.shipping_date = sub.MaxDate

答案 1 :(得分:0)

用于说明的SQL代码 - (这是T-SQL并且对SQL Server友好,但我没有任何mysql方便。最后一个查询应该进行微小修改(以适合您的表名)在MySQL中也能很好地工作

我的逻辑是为每个product_id找到最新的company_order。一旦我有了,我可以加入company_order_id到company_order,并且每个product_id的每个最近的company_order都有shipping_id

DROP TABLE #shipment
DROP TABLE #company_order
DROP TABLE #company_order_item
CREATE TABLE #shipment
    (
      shipment_id INT ,
      shipping_date INT
    ) ;
CREATE TABLE #company_order
    (
      company_order_id INT ,
      shipment_id INT ,
      company_id INT
    ) ;
CREATE TABLE #company_order_item
    (
      company_order_item_id INT ,
      company_order_id INT ,
      product_id INT
    ) ;

INSERT  INTO #shipment
        ( shipment_id , shipping_date )
VALUES
        ( 1 , 1 ),
        ( 2 , 2 ),
        ( 3 , 3 )

INSERT  INTO #company_order
        ( company_order_id , shipment_id , company_id )
VALUES
        ( 1 , 1 , 1 ),
        ( 2 , 2 , 1 ),
        ( 3 , 3 , 1 )

INSERT  INTO #company_order_item
        ( company_order_item_id , company_order_id , product_id )
VALUES
        ( 1 , 1 , 1 )        ,
        ( 2 , 1 , 2 ),
        ( 2 , 2 , 2 ),
        ( 1 , 1 , 3 ),
        ( 1 , 3 , 4 )

SELECT
    product_id ,
    shipment_id
FROM
    (
      SELECT
        product_id ,
        MAX(company_order_id) AS company_order_id
      FROM
        #company_order_item
      GROUP BY
        product_id
    ) AS MostRecentProductInOrder
INNER JOIN #company_order
ON  MostRecentProductInOrder.company_order_id = #company_order.company_order_id