LeetCode 1581. Customer Who Visited but Did Not Make Any Transactions

728x90

 

 

구현 오류

# Write your MySQL query statement below

select distinct v.customer_id, count(v.visit_id) as count_no_trans
from Visits v
where not exists (
  select v.visit_id
  from Visits v, Transactions t
  where v.visit_id = t.visit_id
)
group by v.customer_id;

 

❌ 이유 ❌

WHERE NOT EXISTS 에서 from Visits, Transactions 가 모두 들어간 것이 오류

 

💡 from에 여러개의 table을 넣으면 어떻게 될까?
from 에 2개의 table을 넣게 되면, 2개의 Table이 그냥 Cartesian 곱으로 합쳐짐
즉, 단순결합 !

 

아래 주어진 Table로 예시를 들어보겠어요 

Table Sales , Table Product

 

# Write your MySQL query statement below
select product_name, year, price
from Sales s, Product p

 

위와 같이 쿼리를 짜보면

아래와 같은 Output이 도출되는 것을 통해 합쳐지는 것을 볼 수 있습니다

 

from Sales s, Product p

 

 

즉, 웬만하면 사용을 피하는 게 좋을 거 같다는 판단

 

 

구현

# Write your MySQL query statement below

select distinct v.customer_id, count(v.visit_id) as count_no_trans
from Visits v
where not exists (
  select visit_id
  from Transactions t
  where v.visit_id = t.visit_id
)
group by v.customer_id;

 

🔑 전체적인 구조에서 where의 의미:  where 조건을 만족하는 것을 from Visits 에서 조회하라.

즉, select할 속성이 전부 Visits에서 가져오는 것이기 때문에 첫 번째 from은 Visits 만 있어도 됨

 

✅ where 절

조건에서 가져와서 사용할 속성은 Transactions 안의 visit_id 뿐이므로 from Transactions 만 있어도 됨

where v.vist_id = t.visit_id 에서 v를 사용하고 있다고 해도 속성을 가져올 곳이 v가 아니기 때문에 from에 v 안적어도 됨

 

NOT EXISTS  :  해당 조건을 만족하는 것을 제외하고 조회하는 것 = 해당 조건을 만족하지 않는 것을 조회

(여기서 말하는 조건은 하위 where로 들어가는 조건)

WHERE NOT EXISTS 를 통해 t에도 v에도 중복으로 있는 visit_id (조건)를 만족하지 않는 visit_id를 t 로부터 조회 

where not exists 를 통해 visit_id : 4,6,7,8 해당하는 값 조회

 

 논리 정리

where not exists를 통해 조회한 visit_id : 4,6,7,8 값을 from Visits에서 조회 후

customer_id에 의해 grouping

visit_id   | customer_id

| 4           | 30          |
| 6           | 96          |
| 7           | 54          |
| 8           | 54          |

다음과 같으므로, grouping하면 

customer_id -  count_no_trans

54 - 2

30 - 1

96 - 1

와 같이 될 수 있음

 

💡 distinct 안해도 데이터 조회 가능

조회할 속성은 customer_id와 visit_id의 count 값으로 모두 Visits table에서 가져오는 것
group by v.customer_id로 인해 동일한 customer_id를 가진 값끼리 자동으로 묶임

 

 

Take-aways

 

✅ where 절 안의 부속절은 따로 보기

 

✅ where 절 안에서 전체 절에서 명시한 alias 사용 가능

 

웬만하면 FROM Table1, Table2 ... (FROM 여러개)는 사용을 피하자

      >  해당 사항은 대게 JOIN 연산을 통해서 처리되니까 깔끔하게 JOIN 활용