-- Normalize users_answers.user_id so it always matches the owning registration.
-- Safe to inspect first, then run the UPDATE once on the target database.

SELECT COUNT(*) AS mismatched_rows
FROM users_answers ua
JOIN student_registrations sr ON sr.id = ua.reg_id
WHERE ua.user_id <> sr.user_id;

SELECT
    ua.id,
    ua.exam_id,
    ua.reg_id,
    ua.question_id,
    ua.user_id AS users_answers_user_id,
    sr.user_id AS registration_user_id
FROM users_answers ua
JOIN student_registrations sr ON sr.id = ua.reg_id
WHERE ua.user_id <> sr.user_id
ORDER BY ua.id
LIMIT 100;

UPDATE users_answers ua
JOIN student_registrations sr ON sr.id = ua.reg_id
SET ua.user_id = sr.user_id
WHERE ua.user_id <> sr.user_id;

SELECT COUNT(*) AS mismatched_rows_after_fix
FROM users_answers ua
JOIN student_registrations sr ON sr.id = ua.reg_id
WHERE ua.user_id <> sr.user_id;
