duanruoyu6675 2012-07-14 01:58
浏览 6
已采纳

如何更新我在其中进行SELECT查询的表? (错误#1093)

I am trying to run this:

$stmt=$cxn->prepare("UPDATE table1 SET used='1' WHERE prim_id != 
     (SELECT MAX(prim_id) FROM table1 WHERE email='email12345@gmail.com')");
$stmt->execute(array());

But it results in a MySQL error: #1093 - You can't specify target table 'table1' for update in FROM clause.

After searching this error, it seems that In MySQL, you can't modify the same table which you use in the SELECT part..

How can I change that query to make it work?

Thanks a lot in advance

  • 写回答

2条回答 默认 最新

  • doulan4371 2012-07-14 02:28
    关注

    Try this:

    UPDATE table1 t1, (SELECT MAX(prim_id) AS max_prim_id
                         FROM table1 WHERE email='email12345@gmail.com') tmp
    SET t1.used='1'
    WHERE t1.prim_id != tmp.max_prim_id
    AND t1.`email` = 'email12345@gmail.com'
    

    It removes the subquery and uses a regular temporary table to store the result of table "tmp". The query takes 2 tables for update:

    • table1 (with the alias t1)
    • a temporary table (with the alias tmp)

    The WHERE clause:

    • indicates how the two tables are joined
    • restricts the records to consider in table t1

    The SET clause says that only t1.used will be updated.

    UPDATE statement

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料