Join table with MAX value from another

后端 未结 2 1522
说谎
说谎 2021-01-27 04:17
select * from order
-------------------
|orderID|productID|
-------------------
|  1    |  234    |
|  2    |  234    |
|  3    |  123    |
-------------------

select *         


        
2条回答
  •  感动是毒
    2021-01-27 05:09

    The canonical way of approaching this is to use a subquery to identify the products and their maximum prices from the product_supplier table, and then to join this subquery to order to get the result set you want.

    SELECT t1.orderID,
           t1.productID,
           COALESCE(t2.cost_price, 0.0) AS cost_price  -- missing products will appear
    FROM order t1                                      -- with a zero price
    LEFT JOIN
    (
        SELECT productID, MAX(cost_price) AS cost_price
        FROM product_supplier
        GROUP BY productID
    ) t2
        ON t1.productID  = t2.productID AND
           t1.cost_price = t2.cost_price
    

提交回复
热议问题