select * from order
-------------------
|orderID|productID|
-------------------
| 1 | 234 |
| 2 | 234 |
| 3 | 123 |
-------------------
select *
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 ;
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