V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
cctecoo
V2EX  ›  问与答

In MySQL, you can't modify the same table which you use in the SELECT part. SQL 语句求解答

  •  
  •   cctecoo · 2015-07-03 16:29:06 +08:00 · 1634 次点击
    这是一个创建于 3442 天前的主题,其中的信息可能已经有所发展或是发生改变。

    假设有consume表,其中示例数据如下:

    id money flag history_id
    1 10 1 10
    2 20 2 20
    3 20 2 20
    4 10 2 30

    将含有重复history_id的记录找出,然后update money字段值除以2.
    但是执行sql语句报错.Error Code: You can't specify target table 'consume' for update in FROM clause

    sql语句如下:

    UPDATE consume
    SET 
        money = money / 2
    where
        history_id in (SELECT 
                history_id
            FROM
                consume
            where
                flag = 2
            group by history_id
            having count(history_id) > 1);
    

    请问怎么修改sql语句,求解决方法.

    1 条回复    2015-07-03 17:27:54 +08:00
    rqrq
        1
    rqrq  
       2015-07-03 17:27:54 +08:00   ❤️ 1
    UPDATE consume AS a INNER JOIN (
    SELECT history_id FROM consume WHERE flag = 2 GROUP BY history_id HAVING COUNT(history_id) > 1
    ) AS b ON a.history_id = b.history_id SET money = money / 2
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   5583 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 01:35 · PVG 09:35 · LAX 17:35 · JFK 20:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.