我有这个 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');
但是,它给了我错误:UPDATE 的目标表 A 不可更新
我尝试了多种方法,但都没有成功。我哪里出错了?
另外,如果可以通过任何其他方式将 DB2 查询放入 MySql 中,因为 Mysql 不支持
row_number()
最佳答案
您无法更新派生表。您需要加入真实的表才能更新它。
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
,也许这会达到您想要的效果。
关于mysql - 在更新查询中使用行号 - MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50074477/