您的SQL失敗,你已經使用了AS關鍵字的表連接。
即你應該有:
SELECT q2.Director_ID, q2.Actor_ID
FROM (SELECT MAX(n.Num_Joint_Movies) AS Max_Joint_Movies
FROM (SELECT d.Director_ID, A.Actor_ID, COUNT(*) AS Num_Joint_Movies
FROM Movies_Directors d
, Roles a
where d.Movie_ID = a.Movie_ID
GROUP BY d.Director_ID, A.Actor_ID
) n
) q3,
(SELECT d.Director_ID, A.Actor_ID, COUNT(*) AS Num_Joint_Movies
FROM Movies_Directors d
, Roles a
where d.Movie_ID = a.Movie_ID
GROUP BY d.Director_ID, A.Actor_ID
) q2
where q3.Max_Joint_Movies = q2.Num_Joint_Movies;
你的SQL可以簡化爲這樣的回答:如果我們增加一個等級
SQL> create table Movies_Directors(director_id, Movie_ID)
2 as
3 select 1, 1 from dual
4 union all
5 select 1, 2 from dual
6 union all
7 select 2, 3 from dual
8 union all
9 select 2, 4 from dual
10 union all
11 select 3, 1 from dual ;
Table created.
SQL> create table roles(movie_id, actor_Id)
2 as
3 select 1, 1 from dual union all
4 select 1, 2 from dual union all
5 select 1, 3 from dual union all
6 select 1, 4 from dual union all
7 select 2, 1 from dual union all
8 select 2, 3 from dual union all
9 select 3, 3 from dual union all
10 select 3, 1 from dual;
Table created.
:
select Director_ID, Actor_ID, Num_Joint_Movies
from (select d.Director_ID, A.Actor_ID, COUNT(*) Num_Joint_Movies,
rank() over (order by count(*) desc) r
from Movies_Directors d
inner join Roles a
on d.Movie_ID = a.Movie_ID
group by d.Director_ID, A.Actor_ID)
where r = 1;
編輯一個小樣本分析: SQL> select d.Director_ID,A.Actor_ID,COUNT(*)Num_Joint_Movies, 2秩()以上(以通過計數(*)降序)R 3從Movies_Directorsð 4內連接作用一個 5上d.Movie_ID = a.Movie_ID 6組由d.Director_ID,A.Actor_ID 7/
DIRECTOR_ID ACTOR_ID NUM_JOINT_MOVIES R
----------- ---------- ---------------- ----------
1 1 2 1
1 3 2 1
2 3 1 3
1 2 1 3
3 2 1 3
3 3 1 3
3 4 1 3
2 1 1 3
1 4 1 3
3 1 1 3
10 rows selected.
現在剛過濾的秩1 ..
SQL> select Director_ID, Actor_ID, Num_Joint_Movies
2 from (select d.Director_ID, A.Actor_ID, COUNT(*) Num_Joint_Movies,
3 rank() over (order by count(*) desc) r
4 from Movies_Directors d
5 inner join Roles a
6 on d.Movie_ID = a.Movie_ID
7 group by d.Director_ID, A.Actor_ID)
8 where r = 1;
DIRECTOR_ID ACTOR_ID NUM_JOINT_MOVIES
----------- ---------- ----------------
1 3 2
1 1 2
VS原始(校正的)SQL: SQL> SELECT q2.Director_ID,q2.Actor_ID 2 FROM(SELECT MAX(N .Num_Joint _Movies)AS Max_Joint_Movies 3 FROM(SELECT d.Director_ID,A.Actor_ID,COUNT(*)AS Num_Joint_Movies 4 FROM Movies_Directorsð 5,角色一個 6,其中d.Movie_ID = a.Movie_ID 7 GROUP BY d.Director_ID ,A.Actor_ID 8)N 9)Q3, 10(SELECT d.Director_ID,A.Actor_ID,COUNT(*)AS Num_Joint_Movies 11 FROM Movies_Directorsð 12,角色一個 13其中d.Movie_ID =α。 Movie_ID 14 GROUP BY d.Director_ID,A.Actor_ID 15)Q2 16,在那裏q3.Max_Joint_Movies = q2.Num_Joint_Movies;
DIRECTOR_ID ACTOR_ID
----------- ----------
1 1
1 3
SQL>
小提琴請 - 給我們撥弄鏈接 –
有誰能夠提出一個更好的方式來寫這個查詢... – user1495220