-- List of best differences for each exposure
INSERT INTO magicBestDiffs
SELECT
    rawExp.exp_id,
    warpSkyfile.skycell_id,
    warpSkyfile.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.warp_id = warpSkyfile.warp_id
    AND diffInputSkyfile.skycell_id = warpSkyfile.skycell_id
    AND diffInputSkyfile.template = 0 -- selecting inputs only
JOIN diffSkyfile USING(diff_id)
WHERE
    diffSkyfile.fault = 0
