嵌套内部联接的麻烦

时间:2015-12-11 15:28:42

标签: sql oracle

我有三个看起来像这样的表:

_CONTRACT____________________
|Game_ID|Publisher_ID|Amount|
-----------------------------

Game_ID and Publisher_ID are together the primary key - games can be financed by multiple
publishers and publishers can finance multiple games.

_GAME____
|ID|Name|
---------

PUBLISHER
|ID|Name|
---------

我正在尝试进行一个查询,选择一个表格,该表格会显示最重要的发布商名称(即“合约”表中贡献最多的一个)以及游戏名称和贡献金额。

MOST_SIGNIFICANT_PUBLISHER___
|Game|Publisher|Contribution|
-----------------------------

到目前为止,我已经找到了一张只有最重要的出版商的表格。具有讽刺意味的是,这是更容易的部分,只是在那里获取名称而不是ID,我遇到了麻烦。

所以这里是大多数sig发布者表的选择,其中包含ID而不是名称:

SELECT conTable.*
FROM Contract conTable
INNER JOIN
(
SELECT Game_ID, MAX(Amount) AS MaxAmount
FROM Contract
GROUP BY Game_ID ) grouped
ON conTable.Game_ID = grouped.Game_ID
AND conTable.Amount = grouped.MaxAmount;

这是我对下一步的尝试,以及它产生的错误:

  1  SELECT g.*, p.*, c.*
  2  FROM Game g, Publisher p, Contract c
  3  INNER JOIN
  4  (
  5     SELECT conTable.*
  6     FROM Contract conTable
  7     INNER JOIN
  8     (
  9         SELECT Game_ID, MAX(Amount) AS MaxAmount
 10         FROM Contract
 11         GROUP BY Game_ID) grouped
 12     ON conTable.Game_ID = grouped.Game_ID
 13     AND conTable.Amount = grouped.MaxAmount ) newtable
 14  ON g.ID = newtable.Game_ID
 15  AND p.ID = newtable.Publisher_ID;
AND p.ID = newtable.Publisher_ID
    *
ERROR at line 15:
ORA-00904: "P"."ID": invalid identifier 

我是新手,不知道我的名字有什么问题。 (Publisher确实有一个ID列,Game确实有一个ID列。)

1 个答案:

答案 0 :(得分:1)

正如评论中指出的那样,您正在混合连接语法,这可能会导致麻烦。更不用说你的联接嵌套已经失控了。

row_number分析函数的帮助下,查询可以简化为:

select g.name as game_name,
       p.name as publisher_name,
       c.amount as contribution
  from game g
  join (select game_id,
               publisher_id,
               amount,
               row_number() over (partition by game_id order by amount desc) as rn
          from contract) c
    on c.game_id = g.id
   and c.rn = 1 -- this condition is what limits the results to the most significant contributor for a game
  join publisher p
    on p.id = c.publisher_id