Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Join table with MAX value from another

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...