SELECT
    chipRun.*,
    0 as chip_imfile_id,
    rawImfile.class_id,
    rawImfile.uri,
    rawExp.exp_tag,
    rawExp.exp_name,
    rawExp.camera,
    rawExp.telescope,
    rawExp.filelevel
FROM chipRun
JOIN rawExp
    USING(exp_id)
JOIN rawImfile
    ON rawExp.exp_id = rawImfile.exp_id
    AND rawImfile.ignored = 0
LEFT JOIN chipProcessedImfile
    ON chipRun.chip_id = chipProcessedImfile.chip_id
    AND rawImfile.exp_id = chipProcessedImfile.exp_id
    AND rawImfile.class_id = chipProcessedImfile.class_id
LEFT JOIN chipMask
    ON chipRun.label = chipMask.label
WHERE
    ((chipRun.state = 'new'
    AND chipProcessedImfile.chip_id IS NULL
    AND chipProcessedImfile.exp_id IS NULL
    AND chipProcessedImfile.class_id IS NULL
    AND chipMask.label IS NULL)
    OR
    (chipRun.state = 'update'
    AND chipProcessedImfile.data_state = 'cleaned'))
