0

我在 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

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

谢谢,

贾里德

4

2 回答 2

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 链接)。

于 2013-10-22T22:05:22.607 回答
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
 );
于 2013-10-23T16:08:01.563 回答