MySQL UPDATE with SUBQUERY of same table

后端 未结 2 1746
温柔的废话
温柔的废话 2020-12-03 20:36

I am working with a complex MySQL database table that collects form data. I have simplified the layout in an example table called test below:



        
2条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 21:36

    You have to use a temporary table, because you can't update something you use to select. A simple exemple:

    This will not working :

    UPDATE mytable p1 SET p1.type= 'OFFER' WHERE p1.parent IN 
        (SELECT p2.id from mytable p2 WHERE p2.actu_id IS NOT NULL);
    

    This will do the job:

    UPDATE mytable p1 SET p1.type= 'OFFER' WHERE p1.parent IN 
        (SELECT p2.id from (SELECT * FROM mytable) p2 WHERE p2.actu_id IS NOT NULL);
    

    "from (SELECT * FROM mytable) p2" will create a temporary duplicate of your table, wich will not be affected by your updates

提交回复
热议问题