让我们首先创建一个表-
mysql> create table DemoTable638 (Name varchar(100),Marks int);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable638 values('John',67); mysql> insert into DemoTable638 values('John',90); mysql> insert into DemoTable638 values('David',99); mysql> insert into DemoTable638 values('John',60);
使用select语句显示表中的所有记录-
mysql> select *from DemoTable638;
这将产生以下输出-
+-------+-------+ | Name | Marks | +-------+-------+ | John | 67 | | John | 90 | | David | 99 | | John | 60 | +-------+-------+ 4 rows in set (0.00 sec)
以下是创建返回平均值的函数的查询-
mysql> set global log_bin_trust_function_creators=1; mysql> DELIMITER // mysql> CREATE FUNCTION getAverageDemo() RETURNS INT BEGIN DECLARE value INT; SELECT AVG(Marks) INTO value from DemoTable638 WHERE Name="John"; RETURN value; END; // mysql> DELIMITER ;
现在您可以使用select语句调用该函数-
mysql> select getAverageDemo();
这将产生以下输出-
+------------------+ | getAverageDemo() | +------------------+ | 72 | +------------------+ 1 row in set (0.01 sec)