相当于 MySQL 中 Oracle 的 RowID

2021-11-20 00:00:00 mysql rowid

mysql中是否有相当于oracle的rowid?

is there an equivalent of oracle's rowid in mysql?

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

我想为这个查询创建一个 mysql 等价物!!!

I want to make a mysql equivalent of this query!!!

我想要做的是:my_table 没有主键.. 我正在尝试删除重复的值并强加一个主键(field1、field2 的组合)..!!

What i'm trying to do is, : The my_table has no primary key.. i'm trying to delete the duplicate values and impose a primary key (composite of field1, field2)..!!

推荐答案

在 MySql 中你通常使用会话变量来实现功能:

In MySql you usually use session variables to achive the functionality:

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

但是您无法在子查询中对要从中删除的表进行排序.

But you can not make sorts on the table you are trying to delete from in subqueries.

UPD:也就是说,您需要创建一个临时表,将范围子查询插入临时表并通过加入临时表从原始表中删除(您将需要一些唯一的行标识符):

UPD: that is you will need to create a temp table, insert the ranging subquery to the temp table and delete from the original table by joining with the temporary table (you will need some unique row identifier):

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

既然是一次操作,应该不会带来太多的开销.

Since that is one time operation, this should not bring too much overhead.

相关文章