Home >Database >Mysql Tutorial >How Can I Correctly Retrieve Non-Aggregated Columns with MySQL's MAX() and GROUP BY?
Grouping and Aggregating with MAX() in MySQL
In MySQL, the MAX() function can be used in conjunction with the GROUP BY clause to aggregate data and select the maximum value for a specified column within each group. However, if the target column is not unique within a group, selecting the corresponding non-aggregated columns may yield unexpected results.
To illustrate this issue, let's examine the following SQL query:
SELECT MAX(timestamp), rid, pid FROM theTable GROUP BY rid;
The results of this query may not align with the desired outcome, as the selected pid column might not match the timestamp with the maximum value.
To obtain the correct results, we need to modify the query to identify the rows with the maximum timestamps within each group and then join these rows with the original table to obtain the corresponding pids.
The following modified SQL query accomplishes this:
SELECT test.pid, test.cost, test.timestamp, test.rid FROM theTable AS test INNER JOIN (SELECT rid, MAX(timestamp) AS ts FROM theTable GROUP BY rid) AS maxt ON (test.rid = maxt.rid AND test.timestamp = maxt.ts);
This query first identifies the maximum timestamp for each rid using a subquery, and then joins it with the original table. The join condition ensures that the selected rows are those with the maximum timestamps within each rid group.
As a result, the desired output is obtained:
pid | cost | timestamp | rid |
---|---|---|---|
5 | 345 | 2011-04-14 01:06:06 | 1 |
3 | 4455 | 2011-04-14 01:05:41 | 2 |
7 | 5435 | 2011-04-14 01:14:14 | 3 |
The above is the detailed content of How Can I Correctly Retrieve Non-Aggregated Columns with MySQL's MAX() and GROUP BY?. For more information, please follow other related articles on the PHP Chinese website!