SQL查询,连接多个表,Oracle

时间:2012-05-17 17:43:36

标签: sql join

我有一项任务,我需要编写一个SQL查询,该查询将检索玩家编号以及对于队长并且已经支付超过80英镑的罚款的罚金总额。

我有三张桌子

玩家( playerNo ,姓名,缩写,街道,城镇,邮政编码)

团队( teamNo ,playerNo,division)

处罚( paymentNo ,playerNo,penDate,金额)

粗体文字表示主键。队员表中的球员号码表示队长。

我不知道如何加入三张桌子。但我的尝试是:

SELECT p1.playerNo, SUM(p2.amount)
FROM Players p1 INNER JOIN Teams t
   ON p1.playerNo = t.playerNo 
JOIN penalties p2
   ON p2.playerNo = p1.playerNo
GROUP BY playerNo
HAVING SUM(p2.amount) > 80;

这是否正确?

4 个答案:

答案 0 :(得分:4)

SELECT a.playerNo, a.playerName, SUM(c.amount) as amount, b.teamNo as Team
FROM players a, teams b, penalties c
WHERE a.playerNo = b.playerNo and a.playerNo = c.playerNo
Group By a.playerNo, c.teamNo
Having sum....

答案 1 :(得分:1)

您的查询似乎正确,无法返回您想要的内容。如果同一个玩家是多个团队的队长,那么它确实会打开怎么办的问题,但这可能不会发生。

您想要对数据库结构发表评论吗?

答案 2 :(得分:0)

如果玩家不能成为多个团队的队长,是的,您的查询是正确的。它只需要您将GROUP BY playerNo替换为GROUP BY p1.playerNo

但是如果一名球员可以成为一支以上球队的队长,那么它将会返回错误的结果。无论如何,这将给你一个正确的答案:

SELECT p1.playerNo, SUM(p2.amount)
FROM Players p1 
  JOIN penalties p2
    ON p2.playerNo = p1.playerNo
WHERE EXISTS
      ( SELECT *
        FROM Teams t
        WHERE p1.playerNo = t.playerNo
      ) 
GROUP BY p1.playerNo
HAVING SUM(p2.amount) > 80;

答案 3 :(得分:0)

select captaion_number , sum (amount) total_amount 
from (select t.playes.no   captaion_number , p.amount   amount 
from teams t ,  Penalties p
 where t.player_no = p.player_no ) 
group by captaion_number 
having total_amount > 80 ;