하위 쿼리가 따르는이 상관 하위 쿼리가 외래 키에 대한 널 검사가 아닌 경우 조인으로 대체 할 수 있습니까? 예:
select * from TableABC as t
where
(t.label_id is null or t.label_id in ( select t1.id from Labels as t1 where t1.type = '123'))
and
(t.tag_id is null or t.tag_id in ( select t2.id from Tags as t2 where t2.type = '123'))
단어로 설명 : 레이블 참조가 정의 된 경우 레이블이 특정 유형이어야하는 모든 레코드를 찾고 있다고 가정 해 보겠습니다 . 태그 에도 동일하게 적용됩니다 .
아니면이 쿼리를 다른 방법으로 개선 할 수 있습니까?
TSQL (MS SQL) 용입니다.
업데이트 :
HABO가 암시 한대로 테이블 별칭을 추가했습니다. 가독성이 향상되기를 바랍니다.
이것이 개선 된 것인지는 잘 모르겠지만 left outer join
상관 하위 쿼리 대신 사용 합니다.
-- Sample data.
declare @TableABC as Table( ABCId Int Identity, LabelId Int, TagId Int );
declare @Labels as Table( LabelId Int Identity, Label VarChar(3) );
declare @Tags as Table( TagId Int Identity, Tag VarChar(3) );
insert into @Labels ( Label ) values ( '123' ), ( '12' ), ( '123' );
insert into @Tags ( Tag ) values ( '123' ), ( '213' ), ( '123' ), ( '312' );
insert into @TableABC ( LabelId, TagId ) values
( 1, 1 ), ( 1, 2 ), ( 1, 3 ), ( 1, 4 ),
( 2, 1 ), ( 2, 2 ), ( 2, 3 ), ( 2, 4 ),
( 3, 1 ), ( 3, 2 ), ( 3, 3 ), ( 3, 4 ),
( NULL, 1 ), ( NULL, 3 ), ( 1, NULL ), ( 3, NULL ), ( NULL, NULL );
select ABC.ABCId, ABC.LabelId, ABC.TagId,
L.LabelId as L_LabelId, L.Label as L_Label,
case when ABC.LabelId is NULL or L.Label = '123' then '<<<' else '' end as 'L_Match',
T.TagId as T_TagId, T.Tag as T_Tag,
case when ABC.TagId is NULL or T.Tag = '123' then '<<<' else '' end as 'T_Match'
from @TableABC as ABC left outer join
@Labels as L on L.LabelId = ABC.LabelId left outer join
@Tags as T on T.TagId = ABC.TagId;
-- "Original" query:
select *
from @TableABC
where ( LabelId is null or LabelId in ( select LabelId from @Labels where Label = '123' ) ) and
( TagId is null or TagId in ( select TagId from @Tags where Tag = '123' ) );
-- Left outer joins:
select ABC.*
from @TableABC as ABC left outer join
@Labels as L on L.LabelId = ABC.LabelId and L.Label = '123' left outer join
@Tags as T on T.TagId = ABC.TagId and T.Tag = '123'
where ( ABC.LabelId is NULL or L.LabelId is not NULL ) and ( ABC.TagId is NULL or T.TagId is not NULL );
팁 : 항상 조인과 함께 유용한 테이블 별칭을 사용하고 모든 열에 적용하십시오.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다