SELECT DISTINCT
    pstampDependent.*,
    IFNULL(Label.priority, 10000) AS priority
FROM pstampDependent
JOIN pstampJob USING(dep_id)
JOIN pstampRequest USING(req_id)
LEFT JOIN Label ON pstampRequest.label = Label.label
WHERE pstampDependent.state = 'new'
    AND pstampDependent.fault = 0
    AND pstampJob.state = 'run'
    AND (pstampRequest.state = 'run' OR pstampRequest.state = 'new')
    AND (Label.active OR Label.active IS NULL)
