26

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

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

我想做一个相当于这个查询的mysql!!!

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

4

4 回答 4

32

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

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

但是你不能对你试图从子查询中删除的表进行排序。

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

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

由于这是一次性操作,因此不会带来太多开销。

于 2010-04-28T10:12:54.023 回答
3

也许,我误读了这个问题,但您的查询(即使在 Oracle 中)并没有达到您想要的目标:

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

MySQL等效是

SELECT @rowid:=max(rowid) from my_table;
DELETE FROM my_table where rowid != @rowid;

这将清除除最后一行之外的所有行。

要对数据执行一次清理(删除重复记录),您可以执行以下操作:

CREATE TABLE my_table2 SELECT distinct f1, f2, f3, etc from my_table;
DROP TABLE my_table;
ALTER TABLE my_table2 RENAME my_table;

然后添加 ALTER TABLE 所需的任何列和键。上面的代码可能需要删除您可能拥有的任何外键。

于 2011-11-11T20:46:37.027 回答
1
mysql> set @row_num = 0;

首先设置 rowId 或 row num 使用它如下:

mysql>  SELECT @row_num := @row_num + 1 as row_number,id,name,salary FROM employee
ORDER BY salary;
于 2018-06-11T03:47:30.457 回答
0

您可以使用另一个派生表来避免临时表:

DELETE FROM my_table USING my_table JOIN (
    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) as duplicates
ON my_table.some_row_uid = duplicates.some_row_uid AND duplicates.rowid > 0
于 2010-12-29T20:26:43.497 回答