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

2015-07-03 16:29:06 +08:00
 cctecoo

假设有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语句,求解决方法.

1582 次点击
所在节点    问与答
1 条回复
rqrq
2015-07-03 17:27:54 +08:00
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/203102

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX