SELECT DISTINCT
    exp_id,
    tmp_exp_name,
    tmp_camera,
    tmp_telescope,
    state,
    workdir,
    workdir_state,
    reduction,
    dvodb,
    tess_id,
    end_stage,
    label,
    camera,
    filter,
    obs_mode,
    obs_group,
    epoch,
    dateobs
FROM
    (SELECT
       newExp.*,
       newImfile.tmp_class_id,
       rawImfile.tmp_class_id as raw_tmp_class_id,
       rawImfile.camera,
       rawImfile.filter,
       rawImfile.dateobs,
       rawImfile.obs_mode,
       rawImfile.obs_group
    FROM newExp
    JOIN newImfile
       USING(exp_id)
    LEFT JOIN rawExp
       USING(exp_id)
    LEFT JOIN rawImfile
        ON newImfile.exp_id = rawImfile.exp_id
        AND newImfile.tmp_class_id = rawImfile.tmp_class_id
    WHERE
        newExp.state = 'run'
        AND rawExp.exp_id IS NULL
-- where hook %s
    GROUP BY
        newExp.exp_id
    HAVING
        COUNT(newImfile.tmp_class_id) = COUNT(rawImfile.tmp_class_id)
        AND SUM(rawImfile.fault) = 0
-- limit hook %s
    ) as Foo
