开发者

mysql group by to return a the min value and get the corresponding row data

开发者 https://www.devze.com 2022-12-12 06:52 出处:网络
I have a table of data like so : - PK_table - merchantName - price - Product - 1- argos- 7- 4 - 2- comet- 3- 4

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 re开发者_如何学Pythonsult returned is incorrect since it chooses the first merchant name and not the corresponding merchant of the MIN.

how do you do it?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消