How to select data where a field has a min value in MySQL?

后端 未结 7 1253
半阙折子戏
半阙折子戏 2020-12-02 17:02

I want to select data from a table in MySQL where a specific field has the minimum value, I\'ve tried this:

SELECT * FROM pieces WHERE MIN(price)


        
相关标签:
7条回答
  • 2020-12-02 17:30

    This also works:

    SELECT
      pieces.*
    FROM
      pieces inner join (select min(price) as minprice from pieces) mn
      on pieces.price = mn.minprice
    

    (since this version doesn't have a where condition with a subquery, it could be used if you need to UPDATE the table, but if you just need to SELECT i would reccommend to use John Woo solution)

    0 讨论(0)
  • 2020-12-02 17:31

    To make it simpler

    SELECT *,MIN(price) FROM prod LIMIT 1

    • Put * so it will display the all record of the minimum value
    0 讨论(0)
  • 2020-12-02 17:45

    this will give you result that has the minimum price on all records.

    SELECT *
    FROM pieces
    WHERE price =  ( SELECT MIN(price) FROM pieces )
    
    • SQLFiddle Demo
    0 讨论(0)
  • 2020-12-02 17:49

    Efficient way (with any number of records):

    SELECT id, name, MIN(price) FROM (select * from table order by price) as t group by id
    
    0 讨论(0)
  • 2020-12-02 17:52

    Use HAVING MIN(...)

    Something like:

    SELECT MIN(price) AS price, pricegroup
    FROM articles_prices
    WHERE articleID=10
    GROUP BY pricegroup
    HAVING MIN(price) > 0;
    
    0 讨论(0)
  • 2020-12-02 17:54

    This is how I would do it (assuming I understand the question)

    SELECT * FROM pieces ORDER BY price ASC LIMIT 1
    

    If you are trying to select multiple rows where each of them may have the same price (which is the minimum) then @JohnWoo's answer should suffice.

    Basically here we are just ordering the results by the price in ASCending order (increasing) and taking the first row of the result.

    0 讨论(0)
提交回复
热议问题