Oracle SQL developer에서 self-join에 관련된 query 질문좀 올리겠습니다. 0 3 546

by 머루원해 [2019.02.27 02:33:15]


casting.png (9,145Bytes)
movie.png (28,141Bytes)
actor.png (10,845Bytes)

사용하고 있는 프로그램은 oracle sql developer (oracle 11g) 입니다. self-join 개념이 너무 어렵네요.

Table 정보:

CREATE TABLE actor(
id INTEGER NOT NULL,
name VARCHAR2(100),
CONSTRAINT actor_PK PRIMARY KEY (id));


CREATE TABLE movie(
id INTEGER NOT NULL,
title VARCHAR2(100),
yr NUMBER(4,0),
score NUMBER,
votes INTEGER,
director VARCHAR2(100),
CONSTRAINT movie_PK PRIMARY KEY (id));


CREATE TABLE casting(
movie_id INTEGER NOT NULL,
actor_id INTEGER NOT NULL,
ord INTEGER,
CONSTRAINT casting_PK PRIMARY KEY (movie_id, actor_id),
CONSTRAINT casting_FK1 FOREIGN KEY (movie_id) REFERENCES movie(id),
CONSTRAINT casting_FK2 FOREIGN KEY (actor_id) REFERENCES actor(id));
 

query 문제:

Find all pairs of different actors who played together in more than 30 movies. Show their IDs, names, and the number of movies in which they starred together (label this column as Num_of_Movies). Sort the results in descending order of Num_of_Movies. You need to remove duplicates, i.e., ‘Actor X, Actor Y’ is the same as ‘Actor Y, Actor X’, and only one of them should be displayed.

30개 이상의 영화에 함께 출연했던 다른 배우들의 쌍을 모두 찾아라. 그들의 id, 이름, 그리고 그들이 함께 출연했던 영화의 숫자(alies는 num_of_movies)를 보여줘라. 결과를 num_of_movies desc로 정렬해라. 중복값은 제거되어야 한다. 예를들면, actor x, actor y는 actor y, actor x랑 같은 것이기 때문에 그들 중 한 쌍만 나타나야 한다.

self-join을 여러개 만들어야 한다고 하는 데 무엇을 어떻게 연결해야 될지 모르겠네요. 저는 actor table 2개만들고, casting table과 movie table에 연결해서 4개의 테이블을 사용했는 데 맞는 방법일까요?

샘플은 casting, movie, actor순입니다

by 마농 [2019.02.27 08:27:53]

샘플 데이터는 없나요?

SELECT a.id   a_id
     , a.name a_name
     , b.id   b_id
     , b.name b_name
     , COUNT(*) num_of_movies
  FROM actor a
     , actor b
     , casting c
     , casting d
 WHERE c.actor_id = a.id
   AND d.actor_id = b.id
   AND c.movie_id = d.movie_id
   AND c.actor_id < d.actor_id
 GROUP BY a.id, a.name, b.id, b.name
HAVING COUNT(*) >= 30
 ORDER BY num_of_movies DESC
;

 


by 머루원해 [2019.02.27 10:41:53]

샘플 데이터 올렸습니다. 만약에 title을 select에 넣고 싶으면 movie 테이블만 조인 시키면되는건가요?


by 마농 [2019.02.27 11:13:18]

원본의 문제는 집계쿼리 문제입니다.
집계쿼리에 제목을 추가한다는게 말이 안됩니다.
제목을 추가한다면 집계쿼리가 아닌 목록쿼리가 되어야 하며, 기존 문제와는 전혀 다른 새로운 문제입니다.

댓글등록
SQL문을 포맷에 맞게(깔끔하게) 등록하려면 code() 버튼을 클릭하여 작성 하시면 됩니다.
로그인 사용자만 댓글을 작성 할 수 있습니다. 로그인, 회원가입