update and select the same table problem in mysql

折月煮酒 提交于 2019-12-25 04:08:32

问题


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.



来源:https://stackoverflow.com/questions/4573757/update-and-select-the-same-table-problem-in-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!