Programming-[Backend]/Database

[TIL] 여러 where 조건 한번에 조회하기. multi column related id query join

컴퓨터 탐험가 찰리 2023. 4. 3. 10:12
728x90
반응형

상황

 

base_table에 a, b컬럼이 FK로 잡혀있고, 중복된 항을 count로 구한 결과가 아래와 같을 때

 

 

다시 base_table에서 a_id, b_id를 갖는 id 값을 조회할려면 어떻게 해야할까? 다시 말해 (a_id, b_id) = (9002, 3145), ...인 Row들의 각 id 값을 구하고 싶은 경우 어떻게 해야할까

 

해결 방법

with 구문(또는 서브쿼리)로 원래 SQL문을 감싸고, 기존 테이블과 join을 하되 on절에 원하는 조건을 기입하면 된다.

with tmp as (select count(id),
                    a_id,
                    b_id
             from base_table bt
             where 1 = 1
               and deleted is null
             group by a_id, b_id
             having count(id) > 1)
select bt.id, a_id, b_id from base_table bt
left join tmp on (bt.a_id=tmp.a_id and bt.b_id=tmp.b_id)

 

728x90
반응형