Join table with MAX value from another

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

select *         


        
相关标签:
2条回答
  • 2021-01-27 05:07

    when you need to use aggregate you must use group by and in compare condtion use Having

     SELECT orderID, productID, MAX(cost_price)
     FROM order LEFT JOIN product_supplier 
     ON order.productID=product_supplier.productID having cost_price=MAX(cost_price) group by productID ;
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
提交回复
热议问题