How can rownum be deduplicated in a MySQL query?

In MySQL, there is no built-in function like ROWNUM in Oracle database to achieve row numbering. However, row numbering can be simulated using variables and duplicates can be removed as needed.

Here is a common method to use variables in query results to assign row numbers and remove duplicates based on those row numbers.

SELECT t.* 
FROM (
    SELECT *,
           @rownum := IF(@prev_value = column_to_check, @rownum, @rownum + 1) AS row_number,
           @prev_value := column_to_check
    FROM your_table
    CROSS JOIN (SELECT @rownum := 0, @prev_value := NULL) AS vars
    ORDER BY column_to_check
) AS t
WHERE row_number = 1;

In the above example, replace “column_to_check” with the column you want to deduplicate based on.

This query uses an internal variable (@rownum) to calculate row numbers and another variable (@prev_value) to track the column value of the previous row. For each row, if the column value of the current row is the same as the column value of the previous row, the row number remains unchanged; otherwise, the row number is incremented by 1. Then, the outer query filters out the non-repetitive rows based on the row number.

Please note that the above method is only applicable for removing duplicates on a single column in the query result. If you need to remove duplicates on multiple columns, you will need to make appropriate modifications.

bannerAds