mysql编号行比选择和更新行中的信息

时间:2014-01-01 23:17:13

标签: mysql sql

这有效:

set @type = ' ';  set@num = 1; select * from (select *, @num:= if(@type = firstname, @num + 1, 1) as num, @type := firstname  as dummy from table order by id desc) as table  where table.firstname = 'Mike' and table.num = '2'

这不是

set @type = ' ';  set@num = 1; Update table set table.firstname = 'me' where (select table.firstname from (select *, @num:= if(@type = firstname, @num + 1, 1) as num, @type := firstname as dummy from personal) as table where table.firstname ='Mike' and table.num = '2');

这会更新所有行

set @type = '';  set@num = 1; Update personal set personal.firstname = 'Mike' where personal.firstname in (select personal.firstname from (select firstname, lastname, password, id, @num:= if(@type = firstname, @num + 1, 1) as num, @type := firstname  as dummy from personal order by id desc) as t where t.firstname = 'mike' and num = '1');

更新单个选定行的任何想法

1 个答案:

答案 0 :(得分:0)

请试试这个。如果您正在尝试更新姓名'Mike'的最后创建记录。

set @type = '';  set@num = 1; 
Update personal set personal.firstname = 'NewName' 
 where personal.id in 
 (select t.id from 
  (select firstname, lastname, password, id, 
         @num:= if(@type = firstname, @num + 1, 1)  as num, 
        @type := firstname  as dummy 
      from personal order by firstname,id desc) 
  as t where t.firstname = 'Mike' and num = '1');

如果您想更新名称为“Mike”的Last Created记录,您可以在不使用任何变量的情况下运行更新。

Update personal set personal.firstname = 'NewName' 
 where personal.id in 
     (select t.id from 
        (select id
         from personal 
         where firstname = 'Mike'
         order by id desc LIMIT 1
        )as t 
      );

或者甚至更好,您只需运行此更新

即可
Update personal set personal.firstname = 'NewName' 
       where firstname = 'Mike'
Order by id DESC
Limit 1;