MySQL查看子查询与自定义where子句?

时间:2015-09-25 13:11:25

标签: mysql view subquery

我正在尝试在MySQL数据库上设计一个视图,用于存储有关足球(足球)的信息。

我的目标是创建一个视图,返回记分员的所有目标和基本信息。这是视图的简化版本:

SELECT P.Name AS Player,
       P.TeamName AS Team,
       (SELECT COUNT(*)
        FROM Goals G
        WHERE G.Scorer = P.playerID) AS TotalGoals
FROM Players P

到目前为止,一切都是正确的。当我想在WHERE子句中指定的特定季节内计算目标时,问题就开始了,如下所示:

SELECT * FROM GoalsView WHERE Season = 1

并且它会自动返回WHERE子句中季节目标的计数,就像子查询被自动编辑一样,使其看起来像:

[...]
(SELECT COUNT(*)
FROM Goals G
WHERE G.Scorer = P.playerID
AND Season=1) AS TotalGoals
[...]

我希望自己清楚明白。谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

一种可能的解决方案是

SELECT P.Name AS Player,
   P.TeamName AS Team,
   (SELECT COUNT(*)
    FROM Goals G
    WHERE G.Scorer = P.playerID AND season=1 GROUP By season) AS TotalGoals
 FROM Players P

我不知道你是否有季节或专栏的单独表格

答案 1 :(得分:0)

要访问goals.season,您必须加入两个表:

select 
  p.name as player,
  p.teamname as team,
  count(goals.id) as totalgoals
from players p
left join goals g on g.scorer = p.playerid
group by p.name, p.teamname;