Sport SQL查询改进

时间:2013-05-02 02:50:26

标签: java

如果有人可以帮助我找到适合我桌子的查询,我将不胜感激,因为我经常尝试但只是没有工作。

2 个答案:

答案 0 :(得分:1)

1)

select
  Case when Team.Team_id = Game.Guest_team_id then 'Guest' else 'Home' end as location,
  Team_name,
  Player_name
from Game
join Team on Team.Team_id in (Game.Home_team_id,Game.Guest_team_id)
join Player on Player.team_id = Team.Team_id
order by 1,3

2)假设score扣除Home_team得分 - Guest_team得分:

select Team_Name, TotalPoints = sum(Points)
from (
  select 
    Team_Name, case when score > 0 then 2  
                    when score = 0 then 1 
                                   else 0 end as Points
  from Team join Game on Team.Team_id = Game.Home_team_id
  union all
  select 
    Team_Name, case when score < 0 then 2 
                    when score = 0 then 1 
                                   else 0 end as Points
  from Team join Game on Team.Team_id = Game.Guest_team_id
) T
GROUP BY Team_Name
order by 2 desc
LIMIT 1

这很容易修改,以计算任何特定的感兴趣结果变异。

更新 - 澄清score后:

select Team_Name, TotalPoints = sum(Points)
from (
  select 
    Team_Name, case when home_team_score > guest_team_score then 1
                                                            else 0 
               end as Points
  from Team join Game on Team.Team_id = Game.Home_team_id
  union all
  select 
    Team_Name, case when home_team_score < guest_team_score then 1
                                                            else 0 
               end as Points
  from Team join Game on Team.Team_id = Game.Guest_team_id
) T
GROUP BY Team_Name
order by 2 desc
LIMIT 1

答案 1 :(得分:0)

我会给你一个休息时间,因为MySQL很难开始混乱。您应该研究这些查询的工作原理。如果你正在学习SQL:我个人学习最有效的方法是通过大量练习让我思考不同类型的SQL查询 - 所以做了很多练习。

两队的球员姓名

  

如何以名字显示两个队的所有队员?

我会假设你的意思是球队,而不是游戏。鉴于游戏,请执行以下操作:

SELECT Player.team_id AS team_id,
    Player.player_name AS player_name
FROM Player
INNER JOIN Game
    ON (
        (Game.Home_team_id = Player.team_id)
        OR (Game.Guest_team_id = Player.team_id))
WHERE Game.game_id = [YOUR GAME ID];

这将产生如下结果:

team_id     player_name
1           John Smith
1           Jane Doe
2           John Person

获胜最多的团队

  

我怎样才能找到比其他球队更胜一筹的球队?

由于似乎没有任何说明谁赢了,我真的无法告诉你如何编写这样的查询。只有一个得分字段,我不确定它包含什么。我也不能真正围绕这一点,因为根据可用的数据,查询看起来会有根本的不同,我不喜欢做出假设(这可能是浪费我们两个人的时间)。 / p>

如果它包含JSON或XML数据,或包含一组分数的其他数据格式,则需要将其拆分为自己的单元格。在表格单元格中存储数据集合(例如JSON的分数集合)就可以了 - 只要您永远不会需要查询它。一旦你需要查询它,就会变得一团糟,你需要避免这种情况。