Mysql group to return min value and get corresponding row data

I have a data table like:

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

I want to choose the minimum price for the product and the corresponding seller in mysql.

I tried:

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

however, the returned result is incorrect because it selects the seller’s first name and not the corresponding MIN merchant.

how do you do it

+3
source share
1 answer
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 lines if two dealers have the same low, low price.

+7
source

Source: https://habr.com/ru/post/1723926/


All Articles