创建一个 MySQL 函数并查找列中值的平均值
mysqlmysqli database
首先我们创建一个表 −
mysql> create table DemoTable638 (Name varchar(100),Marks int); Query OK, 0 rows affected (0.68 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable638 values('John',67); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable638 values('John',90); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable638 values('David',99); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable638 values('John',60); Query OK, 1 row affected (0.13 sec)
使用 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; Query OK, 0 rows affected (0.28 sec) 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; // Query OK, 0 rows affected (0.35 sec) mysql> DELIMITER ;
现在您可以使用 select 语句调用函数 −
mysql> select getAverageDemo();
这将产生以下输出 −
+------------------+ | getAverageDemo() | +------------------+ | 72 | +------------------+ 1 row in set (0.01 sec)