Skip to content
GwiyeomGo Tech Blog
About GwiyeomGo

mysql 중복되지 않은 유일한 정보를 추출해보자

MYSQL, 20232 min read

배경

알림톡을 당일에 발송하는 API 는 회원을 조회한다

미전환 회원과 신규 회원을 각각 조회하며 수신자를 수집하는데 쿼리가 제대로 작동하는지 조회해봤다

총 구독자의 memberId 를 조회건에 미전환 회원이 모두 포함되는지 보고싶었다

SELECT distinct member_id FROM
subscribe_data as s
where s.code in(61,
66,
34,
24,
25,
93,
67);
-- 1322 -> ids
SELECT * FROM `members` WHERE `id`
in (
SELECT distinct member_id FROM
subscribe_data as s
where s.code in(61,
66,
34,
24,
25,
93,
67)
) ;
-- 937 (미전환)
select *
where id in(
SELECT distinct member_id FROM
subscribe_data as s
where s.code in(61,
66,
34,
24,
25,
93,
67)
)
;
-- 385 + 937 = 1322
SELECT distinct member_id FROM
subscribe_data as s
where s.code in(
61,
66,
34,
24,
25,
93,
67)
union
SELECT id as member_id
FROM `members` WHERE `id`
in (
SELECT distinct member_id FROM
subscribe_data as s
where s.code in(61,
66,
34,
24,
25,
93,
67)
) ;

=> ids 갑 1322개의 값과 일치 미전환 회원이 모두 포함

union

중복되지 않은 유일한 정보만 추출

20230824 UNION ALL 사용해서 합치기

회원을 통합하면서 회원서비스를 분리했고 기존에 회원테이블과 신규테이블이 생성되었고 총 회원수를 구하고 싶었다 (탈퇴 제외)

-- SELECT count(*) as cnt FROM A
-- 2
-- SELECT count(*) as cnt FROM B
--3
select sum(a.cnt)
from ((SELECT count(*) as cnt FROM A)
UNION ALL
(SELECT count(*) as cnt FROM B )
) as a;
-- 5
  • 중복제거하지 않음 UNION ALL
  • 최소 필요 컬럼만 SELECT 하기

https://donghodazzi.tistory.com/140

© 2024 by GwiyeomGo Tech Blog. All rights reserved.