更新具有重复值的行(在相同列中)

时间:2011-08-30 12:44:11

标签: mysql sql

我想更新我的表,以便共享值(在相同列中)的行被标记为。

示例表定义:

CREATE TABLE `MyTable` (
  `id`  int NOT NULL ,
  `a`  varchar(10) NOT NULL ,
  `b`  varchar(10) NOT NULL , 
  `state`  tinyint NOT NULL , 
  PRIMARY KEY (`id`) 
) ;

我想更新在同一列中共享值的每一行的“状态”。因此,如果第一行具有“a = AAAA”而第二行具有相同的“a”值,则两者都应该更新。

我尝试了这个但是它太慢了(比使用JDBC在Java中更快):

declare mycursor cursor for select id, a, b from mytable;
open mycursor;
repeat
   fetch mycursor into idid, aa, bb;
   update mytable set state=1 where (a=aa, b=bb)
until done end repeat;
close mycursor;

任何改善这种方式的想法?我多年来没有做过任何体面的SQL。

4 个答案:

答案 0 :(得分:7)

尝试第一次查询以查看带有重复项的行 -

SELECT * FROM MyTable t1
  JOIN (
    SELECT a, b FROM MyTable
      WHERE a = 'aa' AND b = 'bb' -- additional condition
      GROUP BY a, b
      HAVING COUNT(*) > 1) t2
  ON t1.a = t2.a AND t1.b = t2.b

尝试这个(基于第一个查询)更新status字段 -

UPDATE MyTable t1
JOIN (
  SELECT a, b FROM MyTable
  WHERE a = 'aa' AND b = 'bb' -- additional condition
  GROUP BY a, b
  HAVING COUNT(*) > 1) t2
ON t1.a = t2.a AND t1.b = t2.b
SET t1.state = 1;

答案 1 :(得分:3)

我的问题的答案似乎如下:

update mytable  as t1 inner join mytable as t2 on (t1.a=t2.a or t1.b = t2.b) and t1.id <> t2.id set t1.state=1;

请说如果不是(似乎有效,但可能做些奇怪的事情);)

答案 2 :(得分:0)

尝试类似......

update MyTable
set state = 1 
where id in (
select id 
from MyTable t1, MyTable t2 
where t1.id <> t2.id 
and t1.a = t2.a 
)

答案 3 :(得分:0)

您不需要光标,只需执行更新语句即可,只要条件成立,所有行都将一次更新。

如果我错过了你的问题并且你确实需要以这种方式浏览每一条记录,你可以轻松地将光标更改为一个简单的while循环,以min(Id)开头,以max(Id)结束。 while循环的执行速度应该比光标快得多。