Obtaining the Lowest Value for Each Dealer in MySQL
Consider a database with the following structure:
CREATE TABLE your_table ( id INT NOT NULL, name VARCHAR(255) NOT NULL, value INT NOT NULL, dealer VARCHAR(255) NOT NULL );
Objective: Retrieve the row with the lowest value for each unique dealer.
Solution:
Solution 1:
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;
Solution 2 (Recommended):
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;
Discussion:
Solution 1 employs a subquery to find the minimum value for each dealer and then joins that information with the original table to collect the complete row data. Solution 2, on the other hand, uses an optimized left join to eliminate any rows with larger values for the same dealer, effectively returning only those with the lowest values.
MySQL provides a dedicated section in its documentation for this frequently encountered scenario, titled "Rows Holding the Group-wise Maximum/Minimum of a Certain Column." Refer to this documentation for further details and examples.
The above is the detailed content of How to Find the Row with the Lowest Value for Each Dealer in MySQL?. For more information, please follow other related articles on the PHP Chinese website!