SELECT DISTINCT
    *
FROM
    (SELECT DISTINCT
        detRun.det_id as det_id,
        detRun.iteration,
        detRun.det_type,
        detRun.workdir,
        rawExp.camera,
        rawExp.telescope,
        rawExp.exp_type,
        detNormalizedImfile.class_id,
        rawImfile.class_id as rawimfile_class_id
    FROM detRun
    JOIN detInputExp
        ON detRun.det_id = detInputExp.det_id
        AND detRun.iteration = detInputExp.iteration
    JOIN rawExp
        ON detInputExp.exp_id = rawExp.exp_id
    JOIN detNormalizedImfile
        ON detInputExp.det_id = detNormalizedImfile.det_id
        AND detInputExp.iteration = detNormalizedImfile.iteration
    LEFT JOIN rawImfile
        ON detInputExp.exp_id = rawImfile.exp_id
        AND detNormalizedImfile.class_id = rawImfile.class_id
    LEFT JOIN detNormalizedExp
        ON detInputExp.det_id = detNormalizedExp.det_id
        AND detInputExp.iteration = detNormalizedExp.iteration
    WHERE
        detRun.state = 'run'
        AND detRun.mode = 'master'
        AND detNormalizedImfile.fault = 0
        AND detNormalizedExp.det_id IS NULL
        AND detNormalizedExp.iteration IS NULL
        AND detInputExp.include = 1
    GROUP BY
        detNormalizedImfile.iteration,
        detRun.det_id
    HAVING
        COUNT(detNormalizedImfile.class_id) = COUNT(rawImfile.class_id)
    ) as Foo
