-- Use a random set of warps for the inputs to a defined stack
INSERT INTO
        stackInputSkyfile(stack_id, warp_id)
SELECT
        @STACK_ID@, -- This should be replaced with the stack_id
        warp_id
FROM (
    -- Sub-select to get the random set of warps
    SELECT
            warpSkyfile.*,
            rand() AS rnd_num
    FROM warpSkyfile
    JOIN warpRun
        USING(warp_id, tess_id)
    JOIN fakeRun
        USING(fake_id, tess_id)
    JOIN camRun
        USING(cam_id, tess_id)
    JOIN chipRun
        USING(chip_id, tess_id)
    JOIN rawExp
        USING(exp_id, tess_id)
    WHERE
        skycell_id = '%s'
        AND tess_id = '%s'
        AND rawExp.filter = '%s'
        AND warpSkyfile.fault = 0
    -- Sort by the random number, and take the first N
    -- to get a random set of N.
    ORDER BY rnd_num
    LIMIT %d
) AS randomWarps
