MySQL 错误您不能在 FROM 子句中为更新指定目标 table

MySQL Error You can't specify target table for update in FROM clause

我的数据库中有 2 个表 MST_customer 和 TRN_sales,其中的条目已损坏。下一个查询 returns 损坏的条目:

SELECT TRN_sales.cust_no 
FROM MST_customer 
RIGHT OUTER JOIN TRN_sales 
ON MST_customer.cust_no = TRN_sales.cust_no 
WHERE MST_customer.cust_name IS NULL;

我试图删除它们执行:

DELETE FROM mydbB.TRN_sales
WHERE TRN_sales.cust_no IN (
  SELECT TRN_sales.cust_no
  FROM MST_customer
  RIGHT OUTER JOIN TRN_sales
  ON MST_customer.cust_no = TRN_sales.cust_no
  WHERE MST_customer.cust_name IS NULL
);

但我收到下一个错误:

You can't specify target table 'TRN_sales' for update in FROM clause

我该如何解决这个问题?

为什么你不尝试以下-

DELETE TRN.*
FROM MST_customer MST
RIGHT OUTER JOIN TRN_sales TRN
ON MST.cust_no = TRN.cust_no 
WHERE MST.cust_name IS NULL;

注意:为了安全起见,在执行此查询之前对两个表进行备份。

要更详细地了解 "the safe side",您应该指定要删除的 table(此处:别名 s),例如:

DELETE s FROM TRN_sales s
LEFT JOIN MST_customers ON MST.cust_no=TRN.cust_no
WHERE MST.cust_name IS NULL;

我个人认为,这个 LEFT JOIN 更容易阅读,当然你可以用你的 RIGHT JOIN 版本做同样的事情。