简体   繁体   English

mysql group by返回一个最小值并获取相应的行数据

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

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. 我希望在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. 但是返回的结果不正确,因为它选择了第一个商家名称,而不是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. 如果两个商人具有相同的低价,低价,则将返回两行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM