INSERT INTO audit_candidate_got_result (CandidateId, OldValue, NewValue, UserId)
SELECT Candidate.Id AS CandidateId,
       0 AS OldValue,
       1 AS NewValue,
       MAX(CandidateAppointment.UserId) AS UserId
FROM
    Candidate
    INNER JOIN Campaign
      ON Candidate.CampaignId = Campaign.Id
    INNER JOIN Course
      ON Campaign.CourseId = Course.Id
    INNER JOIN CandidateAppointment
      ON CandidateAppointment.CandidateId = Candidate.Id AND
         CandidateAppointment.UserId IS NOT NULL
WHERE
    status IN ('present', 'enrolled') AND
    Course.SegmentId != 1 AND
    Candidate.got_result = 0
GROUP BY
    Candidate.Id,
    Candidate.student_name;

CREATE TEMPORARY TABLE tmp (Id int);

INSERT INTO tmp (Id)
SELECT DISTINCT Candidate.Id
FROM
    Candidate
    INNER JOIN Campaign
      ON Candidate.CampaignId = Campaign.Id
    INNER JOIN Course
      ON Campaign.CourseId = Course.Id
    INNER JOIN CandidateAppointment
      ON CandidateAppointment.CandidateId = Candidate.Id AND
         CandidateAppointment.UserId IS NOT NULL
WHERE
    status IN ('present', 'enrolled') AND
    Course.SegmentId != 1 AND
    Candidate.got_result = 0;

UPDATE Candidate SET got_result = 1 WHERE Id in (SELECT Id from tmp);
