Join table with MAX value from another

点点圈 提交于 2021-02-17 02:43:12

问题


select * from order
-------------------
|orderID|productID|
-------------------
|  1    |  234    |
|  2    |  234    |
|  3    |  123    |
-------------------

select * from product_supplier
-------------------------------------------
|ID|supplierID|productID|cost_price|latest|
-------------------------------------------
|1 |  1       | 234     | 1.00     | 0    |
|2 |  1       | 234     | 0.50     | 1    |
|3 |  2       | 123     | 0.75     | 1    |
-------------------------------------------


desired result
------------------------------
|orderID|productID|cost_price|
------------------------------
| 1     | 234     | 1.00     |
| 2     | 234     | 1.00     |
| 3     | 123     | 0.75     |
------------------------------

I'm looking join the two tables above to get the orderID, productID and the largest cost_price for a given productID.

SELECT orderID, productID, cost_price 
FROM order LEFT JOIN product_supplier 
ON order.productID=product_supplier.productID AND MAX(cost_price);

gives ERROR 1111 (HY000): Invalid use of group function

How can i restrict the joined table to one row per order, joined with the largest corresponding cost_price value in product_supplier?


回答1:


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



回答2:


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 ;


来源:https://stackoverflow.com/questions/41849034/join-table-with-max-value-from-another

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!