PHP脚本,可以计算MySQL数据库中列的平均值

时间:2017-02-05 08:33:18

标签: php mysql database

我需要一些关于如何编写我的php脚本的帮助,以便它能找到mysql数据库中六列的平均值,并将新结果存储在mysql数据库中的一个新列中。

例如

MSQL数据库具有以下列

 Name    EXAM1       EXAM2     EXAM3    EXAM4    EXAM5

然后将以下记录输入数据库

 Name    EXAM1       EXAM2     EXAM3    EXAM4    EXAM5


Eric     10          20        10        20       10

然后PHP脚本将生成此结果

 Name    EXAM1       EXAM2     EXAM3    EXAM4    EXAM5     AVERAGE


Eric     10          20        10        20       10         14

因此,在MYSQL数据库中,记录将像PHP脚本结果一样显示。

任何帮助?

感谢。

1 个答案:

答案 0 :(得分:1)

您可以直接在SQL中执行此操作

UPDATE yourTable set AVERAGE = (EXAM1+EXAM2+EXAM3+EXAM4+EXAM5)/5;

如果您按照以下方式定义表格,则自动生成AVERAGE:

CREATE TABLE yourTable (
  title VARCHAR(32) DEFAULT NULL,
  exam1 DOUBLE,
  exam2 DOUBLE,
  exam3 DOUBLE,
  exam4 DOUBLE,
  exam5 DOUBLE,
  average DOUBLE GENERATED ALWAYS AS ((exam1 + exam2 + exam3 + exam4 + exam5) / 5 ) STORED
);

<强>样品

mysql> CREATE TABLE yourTable (
    ->   title VARCHAR(32) DEFAULT NULL,
    ->   exam1 DOUBLE,
    ->   exam2 DOUBLE,
    ->   exam3 DOUBLE,
    ->   exam4 DOUBLE,
    ->   exam5 DOUBLE,
    ->   average DOUBLE GENERATED ALWAYS AS ((exam1 + exam2 + exam3 + exam4 + exam5) / 5 ) STORED
    -> );
Query OK, 0 rows affected (0,02 sec)

mysql> INSERT INTO yourTable (title, exam1, exam2, exam3, exam4, exam5)
    -> VALUES('test1',1,1,22,33,44),('Test2',333,24,11,45,97);
Query OK, 2 rows affected (0,00 sec)
Records: 2  Duplicates: 0  Warnings: 0

mysql>
mysql> SELECT * FROM yourTable;
+-------+-------+-------+-------+-------+-------+---------+
| title | exam1 | exam2 | exam3 | exam4 | exam5 | average |
+-------+-------+-------+-------+-------+-------+---------+
| test1 |     1 |     1 |    22 |    33 |    44 |    20.2 |
| Test2 |   333 |    24 |    11 |    45 |    97 |     102 |
+-------+-------+-------+-------+-------+-------+---------+
2 rows in set (0,00 sec)

mysql>