MySQL:删除包含子选择失败

时间:2013-10-22 22:00:16

标签: mysql

我在MySql中有这个声明:

delete from match_custom_field_team_value
where match_id=10648 
      and match_custom_field_id=14917 
      and event_id in (2, 6, 8, 4)
      and team_id in (select mcfv2.team_id from match_custom_field_team_value mcfv2 
                        where mcfv2.match_id=10648 and mcfv2.match_custom_field_id=14917 and mcfv2.event_id=9);

当我尝试运行时,我得到:

Error Code: 1093. You can't specify target table 'match_custom_field_team_value' for update in FROM clause

知道为什么会抛出错误,以及重写以避免错误的最佳方法吗? (我知道我可以用临时表来做,但宁愿不采取额外步骤。)

谢谢,

贾里德

2 个答案:

答案 0 :(得分:1)

您无法在一个查询中从表中进行选择并从中进行更新/删除。这是禁止的,但你可以用脏的方式解决它。

delete from match_custom_field_team_value
where match_id=10648 
  and match_custom_field_id=14917 
  and event_id in (2, 6, 8, 4)
  and team_id in (
     select * from (
         select mcfv2.team_id from match_custom_field_team_value mcfv2 
            where mcfv2.match_id=10648 and mcfv2.match_custom_field_id=14917 and mcfv2.event_id=9)
     ) as sub
  )

由于MySQL不会在同一个表上运行,而是从该表中获取的结果。 它应该有效,但这不是好方法(例如,考虑性能)。

在使用此查询之前,请先阅读https://dba.stackexchange.com/questions/1371/problem-with-mysql-subquery(@ypercube链接),了解更多可能存在的问题。

答案 1 :(得分:0)

我真的很感谢你的帮助,但我必须继续这样做,所以我用临时表重写了

drop table if exists tmp_cfs_to_nuke;
create temporary table tmp_cfs_to_nuke(
    team_id INT(11) unsigned
);

insert into tmp_cfs_to_nuke 
    select mcfv2.team_id from match_custom_field_team_value mcfv2 
        where mcfv2.match_id=10648 and mcfv2.match_custom_field_id=14917 and mcfv2.event_id=9;

delete from match_custom_field_team_value
where match_id=10648 
  and match_custom_field_id=14917 
  and event_id in (2, 6, 8, 4)
  and team_id in (
    select team_id from tmp_cfs_to_nuke
 );