DELETE FROM media_field_data
WHERE mid IN (
  SELECT mid FROM (
    SELECT media_field_data.mid
    FROM `media_field_data`
    LEFT JOIN media ON media_field_data.mid = media.mid
    WHERE media.mid IS NULL
  ) as foo
);

DELETE FROM media_field_revision
WHERE mid IN (
  SELECT mid FROM (
    SELECT media_field_revision.mid
    FROM `media_field_revision`
    LEFT JOIN media ON media_field_revision.mid = media.mid
    WHERE media.mid IS NULL
  ) as foo
);
