5

I have a table of data like so :

- PK_table - merchantName - price - Product
- 1        - argos        - 7     - 4
- 2        - comet        - 3     - 4
- 1        - Dixon        - 1     - 3
- 1        - argos        - 10    - 4

I wish to select the minimum price for a product and the corresponding merchant in mysql.

I tried:

SELECT Product, merchantName, min(price)
FROM a_table
GROUP BY product

however the result returned is incorrect since it chooses the first merchant name and not the corresponding merchant of the MIN.

how do you do it?

1

1 Answer 1

8
SELECT Merchant.Product, Merchant.Name, Merchant.Price
FROM a_table AS Merchant
JOIN
(
SELECT Product, MIN(Price) AS MinPrice
FROM a_table
GROUP BY Product
) AS Price
ON Merchant.Product = Price.Product
AND Merchant.Price = Price.MinPrice

Will return two rows if two merchants have the same low, low price.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry for bringing up an old thing.. I was wondering if there is a method by which I can achieve this without a subquery. I can do the sub-query because expression inside MIN is complex, time consuming one..
If optimized properly, and you want only a single product, this query will only perform the MIN calculation on the rows it needs. If your engine is not optimizing (and calculation MIN(Whatever) for all products), you can optimize manually by changing FROM a_table to FROM a_table WHERE Product = Some_Product. If you want the query for all products, then you need to use the sub-select, but that's okay because all the calculations are needed for the final result.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.