1

This does not work, I am getting following error. I know why, because I cannot select and update on same tables. Can someone help/guide me in the right direction?

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 Response:

ERROR 1093 (HY000): You can't specify target table 'episode' for update in FROM clause
vick
  • 476
  • 6
  • 18

3 Answers3

1

I would rather use following query:

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';
kseb
  • 712
  • 4
  • 12
0

MySQL doesn't let you update tables which you are using in the select clause. See this answer for more details.

There are several workarounds, one of which is to wrap the select clause with other select statement (warning: inefficient).

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;
Community
  • 1
  • 1
Anthony Accioly
  • 21,918
  • 9
  • 70
  • 118
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
Anup Shah
  • 1,256
  • 10
  • 15