在update query中使用行号-mysql

bvjveswy  于 2021-06-21  发布在  Mysql
关注(0)|答案(2)|浏览(420)

我有一个db2查询,我想使mysql兼容:

UPDATE
(
 SELECT x.name, row_number() over () as rown from XYZ x where x.id = '123' and 
 x.div='abc')A
SET 
 A.name = 'name_1'
where 
A.rown<= ( select count(*) -1 from XYZ where id='123' and div='abc');

现在,我试着写这篇文章:

UPDATE 
(
  select x.name, (@row_number := @row_number +1) as rown 
  from XYZ x, (Select @row_number := 0)as t
  where x.id='123' and x.div='abc'
) A
Set
 A.name = 'name_1'
where
 A.rown<= ( select count(*) -1 from XYZ where id='123' and div='abc');

但是,它给了我一个错误: The target table A of the UPDATE is not updatable 我试过多种方法,但都是徒劳的。我哪里出错了?另外,如果db2查询可以以任何其他方式生成mysql,因为mysql不支持 row_number()

flmtquvp

flmtquvp1#

不能更新派生表。您需要与实际表联接,以便可以更新它。

UPDATE XYZ AS x
JOIN (
    select x.id, (@row_number := @row_number +1) as rown 
    from XYZ x, (Select @row_number := 0) as t
    where x.id='123' and x.div='abc'
) AS A ON x.id = A.id
Set X.name = 'name_1'
where A.rown <= ( select count(*) from XYZ where id='123' and div='abc');

不过,我不确定这是否会与db2查询做同样的事情。它似乎假定表中存在某种固有的排序,也许db2提供了这样的功能,但是mysql不能保证在不使用时的排序 ORDER BY . 如果你加上 ORDER BY x.id 在子查询中,这可能会满足您的要求。

oxalkeyp

oxalkeyp2#

在db2中,您可以做到:

update XYZ f1
set f1.name='name_1'
where f1.id='123' and f1.div='abc' 
and rrn(f1) not in 
( 
   select max(rrn(f2)) from XYZ f2 where f2.id='123' and f2.div='abc'
)

相关问题