@Janaki's answer only provides PROCEDURE
rows if they have a matching TECHNICIAN
row. I would assume, in this case, that either the PROCEDURE
or the TECHNICIAN
could be missing. I would solve this scenario like this:
SELECT rep.rpt_id, tp.tech_id, tp.proc_id
FROM report rep
LEFT JOIN
(SELECT COALESCE (tech.rpt_id, proc.rpt_id) AS rpt_id,
tech.tech_id,
proc.proc_id
FROM technician tech
FULL OUTER JOIN procedure proc
ON proc.proc_id = tech.proc_id) tp
ON tp.rpt_id = rep.rpt_id
WHERE rep.lab_id IN ('test_lab')
The full outer join
ensures that three scenarios are covered: only PROCEDURE
; only TECHNICIAN
; both PROCEDURE
and TECHNICIAN
. The LEFT JOIN
covers the final scenario: no TECHNICIAN
or PROCEDURE
.
Given the clarification (see comments), this query can be simplified:
SELECT rep.rpt_id, tech.tech_id, proc.proc_id
FROM report rep
LEFT JOIN procedure proc ON proc.rpt_id = rep.rpt_id
LEFT JOIN technician tech
ON tech.rpt_id = rep.rpt_id AND proc.proc_id = tech.proc_id
WHERE rep.lab_id IN ('test_lab');
It's important to join to join to PROCEDURE
first, then join TECHNICIAN
based on both preceding tables. This allows for the outer joins to cascade as specified by the clarification properly.