(1093, u"You can't specify target table 'wallet_consume_record' for update in FROM clause") 在 mysql 中使用删除时

(1093, u"You can't specify target table 'wallet_consume_record' for update in FROM clause") when using delete in mysql

我想从 MySQL 5.7 中删除重复数据,这是我的 sql:

DELETE FROM wallet_consume_record 
WHERE trans_no IN (
        SELECT trans_no 
        FROM wallet_consume_record
        GROUP BY trans_no
        HAVING count(trans_no) > 1)
AND id NOT IN (
    SELECT min(id)
    FROM wallet_consume_record
    GROUP BY trans_no
    HAVING count(trans_no) > 1
);

但是当我执行它时,它会抛出:

(1093, u"You can't specify target table 'wallet_consume_record' for update in FROM clause")

我已经试过了:

SET optimizer_switch = 'derived_merge=off';

为什么以及如何让它发挥作用?我也试过包装:

DELETE FROM wallet_consume_record 
WHERE trans_no IN (
        SELECT trans_no 
        FROM wallet_consume_record
        GROUP BY trans_no
        HAVING count(trans_no) > 1)
AND id NOT IN (
    select c.id from 
    (
        SELECT min(id) as id
        FROM wallet_consume_record
        GROUP BY trans_no
        HAVING count(trans_no) > 1
    ) as c
);

还是不行。

mysql root@10.244.5.47:meow_report_pro> select version();
+-------------+
| version()   |
|-------------|
| 5.7.29-log  |
+-------------+
1 row in set
Time: 0.001s

MySQL 不接受在同一查询的 from 子句中引用正在更新或删除的 table。

您可以用 join 来表达:

delete w
from wallet_consume_record w
inner join (
    select trans_no, min(id) min_id
    from wallet_consume_record
    group by trans_no
    having count(*) > 1
) w1 on w.trans_no = w1.trans_no and w.id > w1.min_id 

你可以使用GROUP_CONCAT

制作 2 个用户定义的函数,这些函数 return 对记录的连续值进行分组并在查询中使用它。

即(其中一个函数看起来像)

CREATE FUNCTION `fn_get_tran_no_in_records`()
RETURNS varchar(MAX) CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER

BEGIN

declare var_records varchar(10) default '';

SELECT group_concat(trans_no) 
        FROM wallet_consume_record into var_records 
        GROUP BY trans_no
        HAVING count(trans_no) > 1

return var_records;
END

您可以像这样在查询中简单地使用它

DELETE FROM wallet_consume_record 
WHERE trans_no IN (fn_get_tran_no_in_records());

您可以对 NOT IN 值使用相同的值