update and select the same table problem in mysql

2019-08-24 03:47发布

问题:

hi want to run a query like this:

UPDATE `stories` SET `position`=(select @i:=@i+1) 
WHERE `topic` IN 
    (SELECT `topic` FROM `stories` WHERE `newstype`='2' GROUP BY `topic`)

but target and destination are the same table and mysql doesn't allow me running it. how can i implement it ?

回答1:

you can simulate inner join and update only to first table, like

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;


回答2:

You could always try running the

`SELECT `topic` FROM `stories` WHERE `newstype`='2' GROUP BY `topic`

query first, and then parsing it into a format for use in the IN() in the main query.

Oh wait, I thought I was looking at PHP, not the overall question listing.