강의

멘토링

커뮤니티

Cộng đồng Hỏi & Đáp của Inflearn

Hình ảnh hồ sơ của iceicebear
iceicebear

câu hỏi đã được viết

Bước đầu tiên để kiểm tra mã hóa SQL

cross join, full join

cross join, full join강의 / leetcode 1280번 문제 질문드립니다

Đã giải quyết

Viết

·

286

1

select a.student_id,
a.student_name,
a.subject_name,
count(e.subject_name) attended_exams
from
(
	select student_id,
    	student_name,
    	subject_name
	from Students, Subjects # cross join
) a
left outer join 
(
	select student_id,
	subject_name
	from Examinations
) e
on a.student_id=e.student_id
and a.subject_name=e.subject_name
group by a.student_id, a.student_name, a.subject_name
order by a.student_id, a.subject_name;

해당 코드에 select 문에 있는

count(e.subject_name) attended_exams

를 실행할 때,

count(a.subject_name) attended_exams

와 같이 cross join을 실행한 subject_name을 기준으로 실행하는 경우에는 0값이 안나오는 결과를 확인했는데 둘의 차이가 궁금합니다.

sqlmysql코딩-테스트

Câu trả lời 1

1

Gemma님의 프로필 이미지
Gemma
Người chia sẻ kiến thức

승렬님 안녕하세요:)

늘 참신한 질문을 주셔서 감사합니다.

 

leetcode: https://leetcode.com/problems/students-and-examinations/description/

승렬님의 질문이
위의 코드 (e.subject_name -> 정답 코드)와 아래 코드(a.subject_name -> 오답 코드)의 차이가 무엇이냐로 이해했는데요.

image

image


이해를 위해 아래와 같이 데이터를 좀더 풀어봤습니다. (select *로 확인)

image

왼쪽 노란색 박스는 a temp table에서, 오른쪽 노란색 박스는 e temp table에서 온 결과입니다.

 

참고로 초록색 박스의 row가 왜 3개인지 말씀 드리면,

a temp table에서는 (1, Alice, Math) 조합이 1개이지만, e temp table에서는 (1, Math) 조합이 3개이므로 조인하는 과정에서 3개로 뻥튀기된 것입니다.

 

승렬님의 질문은 분홍색 박스를 확인하면 되는데요.

a temp table에서는 늘 subject_name이 들어있습니다. (분홍색 박스에서 Physics 존재)

반면 e temp table에서는 Examinations table에 없다면 조인할 데이터가 없으므로 null로 나타날 것입니다.

 

null 데이터는 count 자체가 성립이 안되기 때문에, count(null)=0이 됩니다. 그렇기 때문에 우리의 정답 코드처럼 count(e.subject_name)을 하면 0으로 나오는 것입니다.

 

반면 Physics는 count를 할 수 있기 때문에, count(Physics)=1이 됩니다. 그렇게 때문에 오답 코드 처럼 count(a.subject_name)을 하면 늘 1로 나오는 것입니다.


읽어보시고 이해 안가는 부분이 있으시면, 추가 질문 부탁드립니다:)

 

 

Hình ảnh hồ sơ của iceicebear
iceicebear

câu hỏi đã được viết

Đặt câu hỏi