Home  >  Q&A  >  body text

mysql更新语句

下面的表:p_id是父id,old_id是以前的父id,现在需要把p_id的值改成id
比如第一条数据,之前的父id是10,其实对应的是第二跳记录,所以更新后,p_id=2

更新后的结果:

这样的更新语句sql如何写?
需要做的事情:通过p_id找到old_id,这时候的id就是要更新的值;
第一条记录p_id==10,p_id=old_id=10的是第二天记录,把p_id更新成2

ringa_leeringa_lee2743 days ago737

reply all(4)I'll reply

  • 高洛峰

    高洛峰2017-04-17 14:53:26

    I haven’t written a Mysql query operation for a long time, but I have an idea. For the records in the above table, p_id and old_id are in one table, and both comparison operations and update operations are required. Suggestion:

    Step 1: Split a temporary table based on the main table tmp_id, old_tmp_id (corresponding to old_id in the main table)

    • tmp_id old_tmp_id

    • 1 30

    • 2 10

    • 3 20

    Step 2: left join query, where p_id == old_tmp_id, set p_id = tmp_id

    reply
    0
  • 天蓬老师

    天蓬老师2017-04-17 14:53:26

    表名test

    update test t1
    inner join test t2 on t1.p_id = t2.old_id
    set t1.p_id = t2.id

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:53:26

    If you can’t get one SQL statement, just put it in the transaction and update it twice

    reply
    0
  • 阿神

    阿神2017-04-17 14:53:26

    UPDATE test t1
    INNER JOIN test t2 ON t1.p_id = t2.old_id
    SET t1.p_id = t2.id

    reply
    0
  • Cancelreply