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)
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
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
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!