-- List of best differences for each exposure
INSERT INTO magicBestDiffs
SELECT
    exp_id,
    warpSkyfile.skycell_id,
    warpSkyfile.tess_id,
    MAX(diffSkyfile.diff_id) AS diff_id
FROM rawExp
JOIN chipRun USING(exp_id, tess_id)
JOIN camRun USING(chip_id, tess_id)
JOIN fakeRun USING(cam_id, tess_id)
JOIN warpRun USING(fake_id, tess_id)
JOIN warpSkyCellMap USING(warp_id, tess_id)
JOIN warpSkyfile USING(warp_id, skycell_id, tess_id)
JOIN diffInputSkyfile
    ON diffInputSkyfile.warp_id = warpSkyfile.warp_id
    AND diffInputSkyfile.skycell_id = warpSkyfile.skycell_id
    AND diffInputSkyfile.tess_id = warpSkyfile.tess_id
    AND diffInputSkyfile.template = 0 -- selecting inputs only
JOIN diffSkyfile USING(diff_id)
WHERE
    diffSkyfile.fault = 0
