MySQL选择更新指南,查询不执行

时间:2013-10-11 23:31:39

标签: mysql

这不起作用,我收到以下错误。我知道为什么,因为我不能在同一个表上选择和更新。有人可以帮助/指导我朝正确的方向发展吗?

update 
    episode 
set 
    update_wp = 1 
where 
    episode_id in(
        select 
            e.episode_id 
        from 
            collection c 
        inner join 
            season s on s.collection_id = c.collection_id 
        inner join 
            episode e on e.season_id = s.season_id  
        where 
            c.title ='mom'
        );

MySQL响应:

ERROR 1093 (HY000): You can't specify target table 'episode' for update in FROM clause

3 个答案:

答案 0 :(得分:1)

我宁愿使用以下查询:

UPDATE episode e, collection c, season s 
   SET e.update_wp = 1 
   WHERE 
     e.season_id = s.season_id AND 
     s.collection_id = c.collection_id AND 
     c.title = 'mom';

答案 1 :(得分:0)

MySQL不允许您更新您在select子句中使用的表。 有关详细信息,请参阅this answer

有几种解决方法,其中一种方法是使用其他select语句包装select子句(警告:效率低下)。

update 
    episode 
set 
    update_wp = 1 
where 
    episode_id in (
      select in_episode_id from (
        select 
            e.episode_id as in_episode_id
        from 
            collection c 
        inner join 
            season s on s.collection_id = c.collection_id 
        inner join 
            episode e on e.season_id = s.season_id  
        where 
            c.title ='mom'
      )
    ) as x;

答案 2 :(得分:0)

    update t1
    set 
        t1.update_wp = 1 
    from episode t1
    join
    (
            select 
                e.episode_id 
            from 
                collection c 
            inner join 
                season s on s.collection_id = c.collection_id 
            inner join 
                episode e on e.season_id = s.season_id  
            where 
                c.title ='mom'
    )t2
    t1.episode_id=t2.episode_id