데이터과학 삼학년

[DB] JOIN condition에 OR 포함? 본문

Data Visualization & DataBase

[DB] JOIN condition에 OR 포함?

Dan-k 2022. 11. 26. 17:25
반응형

여러 테이블이 있을때 조인 condition 조건으로 or를 쓰고 싶을 때가 있다.

join 조건에 OR을 넣으면 union과 같이 데이터의 갯수가 늘어날수 밖에 없다는 것 명심하자!!!!!!

 

근데, 웬만하면 join 컨디션에 OR 쓰지 말자.

이유는 SQL서버의 최적화가 제대로 작동하지 않는다고 한다.

join은  HASH join 이나 MERGE join에 최적화되지 않는다.

즉, join의 최적화는 인덱스 매칭으로 이루어지는데 조건절에 OR조건이 포함되면 인덱스를 타지못해 성능이 현저히 떨어진다.

 

만약 join 컨디션에 OR을 넣은 아래와 같은 쿼리를 날리려고 한다면,

SELECT mt.ID, mt.ParentID, ot.MasterID
  FROM dbo.MainTable AS mt
  INNER JOIN dbo.OtherTable AS ot ON ot.ParentID = mt.ID
                                  OR ot.ID = mt.ParentID

LEFT JOIN으로 연결하거나, UNION ALL로 연결하는 방식을 취하자.

SELECT mt.ID, mt.ParentID,
   CASE WHEN ot1.MasterID IS NOT NULL THEN
      ot1.MasterID ELSE
      ot2.MasterID END AS MasterID
  FROM dbo.MainTable AS mt
  LEFT JOIN dbo.OtherTable AS ot1 ON ot1.ParentID = mt.ID
  LEFT JOIN dbo.OtherTable AS ot2 ON ot2.ID = mt.ParentID
  WHERE ot1.MasterID IS NOT NULL OR ot2.MasterID IS NOT NULL
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

 

참조

https://stackoverflow.com/questions/5901791/is-having-an-or-in-an-inner-join-condition-a-bad-idea

 

Is having an 'OR' in an INNER JOIN condition a bad idea?

In trying to improve the speed of an immensely slow query (several minutes on two tables with only ~50,000 rows each, on SQL Server 2008 if it matters), I narrowed down the problem to an OR in my i...

stackoverflow.com

 

728x90
반응형
LIST
Comments