我的查询是:
set @csum := 0;
update `aaa` INNER JOIN
`bbb`
ON `bbb`.`id`=`aaa`.`tid`
set `aaa`.`tc` = (@csum := @csum + 1)
WHERE `aaa`.`tid` IN (6,7)
ORDER BY `bbb`.`priority` ASC, `aaa`.`floor` ASC, `aaa`.`id` ASC;
但返回错误#1221 - Incorrect usage of UPDATE and ORDER BY
我该如何执行此查询? 我需要从第一个记录到最后一个记录进行排序和更新
答案 0 :(得分:0)
试试这个:
set @csum = 0;
update set aaa.tc = (@csum + 1),@csum=@csum+1
from aaa INNER JOIN bbb ON bbb.id=aaa.tid WHERE aaa.tid IN (6,7)
我并不认为在更新的情况下需要按顺序排序。
答案 1 :(得分:0)
这非常棘手。 MySQL不允许order by
update
使用join
。但是,您的查询需要order by
的两个表。
以下选择似乎返回您想要的内容:
select aaa.*, (@csum := @csum + 1) as csum
from `aaa` join
`bbb`
on `bbb`.`id` = `aaa`.`tid` cross join
(select @csum := 0) params
where `aaa`.`tid` IN (6, 7)
order by `bbb`.`priority` ASC, `aaa`.`floor` ASC, `aaa`.`id` ASC;
您现在可以将其合并到update
:
update aaa join
(select aaa.*, (@csum := @csum + 1) as csum
from `aaa` join
`bbb`
on `bbb`.`id` = `aaa`.`tid` cross join
(select @csum := 0) params
where `aaa`.`tid` IN (6, 7)
order by `bbb`.`priority` ASC, `aaa`.`floor` ASC, `aaa`.`id` ASC
) aaaa
on aaaa.id = aaa.id
set `aaa`.`tc` = csum;