我Table A
引用了Table B
。对于A中的每条记录,Table B
可能有一个或多个条目。在B中,我有一列作为状态。我想在下面的给定条件下选择一行。考虑我在Table B
我的查询
--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
这是正确的方法吗?它会对性能产生影响吗?真的很想在这里强调,实际上我必须加入近10张表,其中5张将有10万张以上的记录。
答案 0 :(得分:0)
cross/outer apply (
select top 1 status
from B b
where b.id = a.id
order by case when status in ('OA', 'OB') then 1 else 2 end, status
)
或
inner/left join (
select
id,
case min(case when status in ('OA', 'OB') then 1 else 2 end)
when 1 then min(cast when status in ('OA', 'OB') then status end)
when 2 then min(status)
end
from B
group by id
) b on b.id = a.id