使用存储过程计算团队中的人员

时间:2012-05-23 03:41:08

标签: mysql sql join stored-procedures

我想创建一个接受团队名称和年份的存储过程,并返回该特定团队中该特定团队的玩家数量。我正在使用MYSQL,下面列出了我正在使用的表:

Person     (personID, name, phone, email, year)
Player     (personID, dateOfBirth, school)
playerTeam (personID, teamID)
Team       (teamID, teamName, ageGroup)

到目前为止,我已尝试加入表格并仅在teamID和Person.year =输入参数的情况下宣传personID,但无济于事。有什么想法吗?

提交此问题后,使用反复试验,我能够使用以下语句使其工作:

DELIMITER //

CREATE PROCEDURE teamSize (IN team VARCHAR (30), IN YEAR INT) 
BEGIN
          SELECT 
                    COUNT(Person.personID) NumOfPlayers 
          FROM
                    Person AS p,
                    Player,
                    playerTeam,
                    Team 
          WHERE Person.personID = Player.personID 
                    AND Player.personID = playerTeam.personID 
                    AND Team.teamID = playerTeam.teamID 
                    AND Team.teamName = team 
                    AND Person.year = YEAR ;
END //

DELIMITER ;

CALL teamSize('Pirates', 1991);

无论如何使用连接等来简化它,因为它有点乱。

1 个答案:

答案 0 :(得分:2)

我不确定你是否想这样:

DELIMITER //

CREATE PROCEDURE GetPlayerCount (
          IN oTeamName VARCHAR (50),
          IN oYear INT
) AS 
BEGIN
          SELECT 
                    COUNT(a.PersonID) NoOfPlayers 
          FROM
                    Person a 
                    INNER JOIN PlayerTeam b 
                              ON a.PersonID = b.PersonID 
                    INNER JOIN Team c 
                              ON b.TeamID = c.TeamID 
          WHERE b.TeamName = oTeamName 
                    AND a.Year = oYear ;
END //

DELIMITER ;

但我认为这是你想要的。

用法:

CALL GetPlayerCount('TeamDog', 2012);