我有这个 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');
现在,我尝试写这个 MySQL :
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()
答案 0 :(得分:0)
您无法更新派生表。您需要加入真实表,以便更新它。
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提供了这样的东西,但是当你不使用ORDER BY
时,MySQL不会对排序做出任何保证。如果您在子查询中添加ORDER BY x.id
,那么可能会执行您想要的操作。
答案 1 :(得分:0)
在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'
)