-- List of best differences for each exposure
INSERT INTO magicBestDiffs
SELECT
    rawExp.exp_id,
    diffInputSkyfile.skycell_id,
    diffInputSkyfile.tess_id,
    MAX(diffSkyfile.diff_id) AS diff_id
FROM rawExp
JOIN chipRun USING(exp_id)
JOIN camRun USING(chip_id)
JOIN fakeRun USING(cam_id)
JOIN warpRun USING(fake_id)
JOIN warpSkyCellMap USING(warp_id)
JOIN warpSkyfile USING(warp_id, skycell_id)
JOIN diffInputSkyfile
    ON diffInputSkyfile.warp1 = warpSkyfile.warp_id
    AND diffInputSkyfile.skycell_id = warpSkyfile.skycell_id
JOIN diffRun USING(diff_id)
JOIN diffSkyfile USING(diff_id)
WHERE
    diffSkyfile.fault = 0
-- WHERE hook %s
GROUP BY
    exp_id,
    diffInputSkyfile.skycell_id,
    diffInputSkyfile.tess_id
;
