在mysql中更新并选择相同的表问题

在mysql中更新并选择相同的表问题,mysql,sql-update,Mysql,Sql Update,希望运行如下查询: UPDATE `stories` SET `position`=(select @i:=@i+1) WHERE `topic` IN (SELECT `topic` FROM `stories` WHERE `newstype`='2' GROUP BY `topic`) 但是目标和目标是同一个表,mysql不允许我运行它。 如何实现它?您可以尝试运行 `SELECT `topic` FROM `stories` WHERE `newstype`='2' GRO

希望运行如下查询:

UPDATE `stories` SET `position`=(select @i:=@i+1) 
WHERE `topic` IN 
    (SELECT `topic` FROM `stories` WHERE `newstype`='2' GROUP BY `topic`)
但是目标和目标是同一个表,mysql不允许我运行它。
如何实现它?

您可以尝试运行

`SELECT `topic` FROM `stories` WHERE `newstype`='2' GROUP BY `topic`
首先查询,然后将其解析为在主查询的in()中使用的格式


哦,等等,我想我是在看PHP,而不是整个问题列表。

您可以模拟内部连接,并只更新到第一个表,如

set @pos:=0; 
update 
  stories a, 
  (select topic, @pos:=@pos+1 as new_position 
   from stories 
   where newstype=2 group by topic
  ) as b 
set a.position=b.new_position 
where a.topic=b.topic;