CREATE TEMPORARY TABLE media_category_keep AS
SELECT MIN(id) AS keep_id, user_id, slug
FROM media_categories
WHERE content_type = 'music' AND scope = 'user' AND radio_id IS NULL
GROUP BY user_id, slug;

UPDATE media_files f
INNER JOIN media_categories c ON c.id = f.category_id
INNER JOIN media_category_keep k ON k.user_id = c.user_id AND k.slug = c.slug
SET f.category_id = k.keep_id
WHERE c.content_type = 'music'
  AND c.scope = 'user'
  AND c.radio_id IS NULL
  AND c.id <> k.keep_id;

DELETE c
FROM media_categories c
INNER JOIN media_category_keep k ON k.user_id = c.user_id AND k.slug = c.slug
WHERE c.content_type = 'music'
  AND c.scope = 'user'
  AND c.radio_id IS NULL
  AND c.id <> k.keep_id;

DROP TEMPORARY TABLE media_category_keep;
