我有以下查询:
SET @year1 = 2011;
select B.YearID, sum(B.ab), sum(B.h), sum(B.h)/ sum(B.ab)
From Batting B join Pitching P
on (P.playerID = B.playerID and B.yearID = P.yearid and B.ab > 0 )
where B.yearid = @year1
这可以很好地检索一年的结果。但是我可以在mySQL上使用循环来执行查询并查看每年的结果吗?
此代码不起作用并产生语法错误:
SET @year1 = 2011;
While @year1 <= 2014 DO
SET @year1 = @year1 + 1;
select B.YearID, sum(B.ab), sum(B.h), sum(B.h)/ sum(B.ab)
From Batting B join Pitching P
on (P.playerID = B.playerID and B.yearID = P.yearid and B.ab > 0 )
where B.yearid = @year1;
End While
我可以在MySQL中编写查询,还是必须使用PHP等语言?
答案 0 :(得分:1)
最简单的方法是使用group by:
select B.YearID, sum(B.ab), sum(B.h), sum(B.h)/ sum(B.ab)
From Batting B join Pitching P
on (P.playerID = B.playerID and B.yearID = P.yearid and B.ab > 0 )
where b.yearid>=2011 and b.yearid<=2014
group by B.yearid;
这将立即为您提供列表。
在存储过程中也可以使用循环,但出于语法原因,您必须使用WHILE:
CREATE PROCEDURE someProcedure(IN start_year INT, end_year INT)
BEGIN
DECLARE v_year_id INT;
SET v_year_id=start_year;
WHILE(v_year_id<end_year)
LOOP
select B.YearID, sum(B.ab), sum(B.h), sum(B.h)/ sum(B.ab)
From Batting B join Pitching P
on (P.playerID = B.playerID and B.yearID = P.yearid and B.ab > 0 )
WHERE yearId=v_year_id;
group by B.yearid;
SET v_year_id=v_year_id+1;
END WHILE;
END;
也可以删除局部变量v_year_id,但为了清楚起见,此处已添加。如果消除v_year_id,它将如下所示:
CREATE PROCEDURE someProcedure(IN start_year INT, end_year INT)
BEGIN
WHILE(start_year<end_year)
LOOP
select B.YearID, sum(B.ab), sum(B.h), sum(B.h)/ sum(B.ab)
From Batting B join Pitching P
on (P.playerID = B.playerID and B.yearID = P.yearid and B.ab > 0 )
WHERE yearId=start_year;
group by B.yearid;
SET start_year=start_year+1;
END WHILE;
END;
调用程序将通过以下方式完成:
CALL someProcedure(2011,2014);