Home > Database > Mysql Tutorial > body text

How to Efficiently Return the Last Row of Each Group in MySQL?

DDD
Release: 2024-11-11 20:29:02
Original
618 people have browsed it

How to Efficiently Return the Last Row of Each Group in MySQL?

Return the Last Row of Each Group in MySQL Effectively

Returning the last row of each group in MySQL is often necessary for data manipulation. The query provided in the prompt:

select * 
    from foo as a
    where a.id = (select max(id) from foo where uid = a.uid group by uid)
    group by uid;
Copy after login

achieves this by performing a nested query to find the maximum ID for each unique UID, then selecting only the rows with the matching ID.

A More Efficient Approach

However, a more efficient query can be used to eliminate the nested query:

SELECT t1.* 
FROM foo t1
JOIN (
    SELECT uid, MAX(id) AS max_id 
    FROM foo 
    GROUP BY uid
) t2 ON t1.id = t2.max_id;
Copy after login

This query uses a JOIN operation to directly match the maximum ID for each UID, providing improved performance compared to the nested query approach.

Additional Optimization Considerations

For further optimization, EXPLAIN can be used to analyze the query plan and identify any potential bottlenecks. Additionally, an index on the UID column can significantly enhance query performance.

Alternative Approach

Another option is to use the LAG() function:

SELECT t1.* 
FROM foo t1
LEFT JOIN foo t2
ON t1.id < t2.id AND t1.uid = t2.uid
WHERE t2.id is NULL;
Copy after login

This query uses the LAG() function to identify the next row in the group. If there is no subsequent row (i.e., the current row is the last in its group), the query will return the current row. While this approach can be efficient, it may not always be as performant as the JOIN-based queries discussed above.

The above is the detailed content of How to Efficiently Return the Last Row of Each Group in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template