Home > Database > Mysql Tutorial > Does MySQL Have a ROWID Equivalent for Deleting Duplicate Records?

Does MySQL Have a ROWID Equivalent for Deleting Duplicate Records?

Linda Hamilton
Release: 2024-12-09 20:20:15
Original
522 people have browsed it

Does MySQL Have a ROWID Equivalent for Deleting Duplicate Records?

MySQL Equivalent of Oracle's RowID

In Oracle, the ROWID column uniquely identifies each row in a table. Is there an equivalent column in MySQL?

The question often arises when performing operations such as deleting duplicate records while imposing a primary key, as in the query provided:

delete from my_table where rowid not in (select max(rowid) from my_table group by field1,field2)
Copy after login

MySQL Solution

Unlike Oracle, MySQL does not have a direct equivalent to ROWID. Instead, you can use session variables to generate a unique row identifier:

SELECT @rowid:=@rowid+1 as rowid
FROM table1, (SELECT @rowid:=0) as init
ORDER BY sorter_field
Copy after login

However, this approach cannot be used in subqueries that sort on the target table being deleted from.

Alternative Approach

To delete duplicate records and enforce a primary key, you can create a temporary table to store the unique row identifiers:

CREATE TEMPORARY TABLE duplicates ...

INSERT INTO duplicates (rowid, field1, field2, some_row_uid)
SELECT
  @rowid:=IF(@f1=field1 AND @f2=field2, @rowid+1, 0) as rowid,
  @f1:=field1 as field1,
  @f2:=field2 as field2,
  some_row_uid
FROM testruns t, (SELECT @rowid:=NULL, @f1:=NULL, @f2:=NULL) as init
ORDER BY field1, field2 DESC;

DELETE FROM my_table USING my_table JOIN duplicates
  ON my_table.some_row_uid = duplicates.some_row_uid AND duplicates.rowid > 0
Copy after login

This approach creates a temporary table, inserts the unique row identifiers, and then uses a join to delete duplicate records from the original table. While it adds a minor overhead, it is a viable solution for one-time operations.

The above is the detailed content of Does MySQL Have a ROWID Equivalent for Deleting Duplicate Records?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template