I have Table A
which have reference to Table B
. Table B
may have one or more entry for each record in A. In B I have a column as status. I want to choose one row by given condition below. Consider I have 3 entries in Table B
- If status is OA or OB in any row, then select that row
- If status is other than OA or OB then select any one row
My query
--lot more table joins already here
LEFT JOIN(
SELECT CASE WHEN EXISTS
( SELECT 1 FROM A a1 INNER JOIN B b1 ON a1.id = b1.id
WHERE b1.status in ('OA','OB'))
THEN (SELECT b1.rcid FROM A a1 INNER JOIN B b1 ON a1.id = b1.id
WHERE b1.status in ('OA','OB'))
ELSE
SELECT TOP 1 b2.rcid FROM A a2 INNER JOIN B b2 ON a2.id = b2.id
END
))Z on z.id=b2.id --again join with table for b2.rcid
Is this the correct way? Will it have a performance impact?. Really want to highlight here, in real I have to join almost 10 tables of which 5 will have 100 000+ records.