表被指定两次,既作为 'UPDATE' 的目标,也作为 mysql 中数据的单独源

2021-11-20 00:00:00 mysql

我在 mysql 中有以下查询,我想检查 branch id 和 year 的 finance 类型是否来自 branch_master 与 manager 的 branch id 和 year 相等,然后更新状态manager 表对 manager 中的 branch id

I have below query in mysql where I want to check if branch id and year of finance type from branch_master are equal with branch id and year of manager then update status in manager table against branch id in manager

UPDATE manager as m1 
  SET m1.status = 'Y'
  WHERE m1.branch_id IN (
    SELECT m2.branch_id FROM manager as m2 
     WHERE (m2.branch_id,m2.year) IN (
        (
          SELECT DISTINCT branch_id,year 
            FROM `branch_master` 
           WHERE type = 'finance'
        )
     )
  )

但出现错误

表 'm1' 被指定两次,既作为 'UPDATE' 的目标,也作为单独的数据来源

Table 'm1' is specified twice, both as a target for 'UPDATE' and as a separate source for data

推荐答案

这是一个典型的 MySQL 事情,通常可以通过从表中选择来规避,即代替

This is a typical MySQL thing and can usually be circumvented by selecting from the table derived, i.e. instead of

FROM manager AS m2

使用

FROM (select * from manager) AS m2

完整声明:

UPDATE manager
SET status = 'Y'
WHERE branch_id IN
(
  select branch_id
  FROM (select * from manager) AS m2
  WHERE (branch_id, year) IN
  (
    SELECT branch_id, year
    FROM branch_master
    WHERE type = 'finance'
  )
);

相关文章