sagan of sanga

saga of mine

Monday, March 31, 2014

When you need to query & update in the same table

Would you use sub-query?

# 3D movies are linked to corresponding 2D movies with parent_id
# some movies don't have that link, we need to update them
# by looking for movies with almost the same title (such as "Avatar 3D" and "Avatar")
#
UPDATE `cine_movies` D, (
    #SELECT A.movie_id, A.title, B.title, B.movie_id parent_id
    SELECT A.movie_id, B.movie_id parent_id
    FROM (
        SELECT `title`, `movie_id` FROM `cine_movies` 
        WHERE  `title` LIKE '% 3D%' AND `parent_id` = '0'
    ) A
    INNER JOIN `cine_movies` B ON B.title = replace(A.title, ' 3D', '')
) C
SET   D.parent_id = C.parent_id

WHERE C.movie_id  = D.movie_id;

0 Comments:

Post a Comment

<< Home