MYSQL如何选择字段具有最小值的数据

Sam*_*ali 30 mysql sql aggregate-functions greatest-n-per-group

我想从表中选择数据,其中特定字段具有最小值,我试过这个:

SELECT * FROM pieces where min(price)
Run Code Online (Sandbox Code Playgroud)

我对MySQL不好,请帮忙吗?谢谢

Joh*_*Woo 56

这将为您提供所有记录的最低价格结果.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )
Run Code Online (Sandbox Code Playgroud)

  • 那可能很慢. (6认同)

sbe*_*rry 43

我就是这样做的(假设我理解这个问题)

SELECT * FROM pieces ORDER BY price ASC LIMIT 1
Run Code Online (Sandbox Code Playgroud)

如果您尝试选择多行,其中每行可能具有相同的价格(这是最小值),那么@ JohnWoo的答案应该足够了.

基本上我们只是按ASCending顺序(增加)中的价格排序结果并取结果的第一行.


fth*_*lla 5

这也有效:

SELECT
  pieces.*
FROM
  pieces inner join (select min(price) as minprice from pieces) mn
  on pieces.price = mn.minprice
Run Code Online (Sandbox Code Playgroud)

(因为这个版本没有带子查询的 where 条件,如果你需要更新表可以使用它,但如果你只需要 SELECT 我会建议使用 John Woo 解决方案)


小智 5

使用HAVING MIN(...)

就像是:

SELECT MIN(price) AS price, pricegroup
FROM articles_prices
WHERE articleID=10
GROUP BY pricegroup
HAVING MIN(price) > 0;
Run Code Online (Sandbox Code Playgroud)


小智 5

有效的方式(具有任意数量的记录):

SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
Run Code Online (Sandbox Code Playgroud)