MySQL - Fetching lowest value

后端 未结 7 1265
醉酒成梦
醉酒成梦 2020-12-06 03:14

My database structure contains columns: id, name, value, dealer. I want to retrieve row with lowest value for each dealer

7条回答
  •  既然无缘
    2020-12-06 03:40

    Solution1:

    SELECT t1.* FROM your_table t1
    JOIN (
      SELECT MIN(value) AS min_value, dealer
      FROM your_table 
      GROUP BY dealer
    ) AS t2 ON t1.dealer = t2.dealer AND t1.value = t2.min_value
    

    Solution2:

    SELECT t1.* FROM your_table t1
    LEFT JOIN your_table t2
    ON t1.dealer = t2.dealer AND t1.value > t2.value
    WHERE t2.value IS NULL
    

    This problem is very famous, so there is a special page for this in Mysql's manual.

    Check this: Rows Holding the Group-wise Maximum/Minimum of a Certain Column

提交回复
热议问题