我在表num1
,num2
,num3
中有3个字段。
我需要在另一个字段avgNum
中平均这三个。
用户只能使用插入查询插入num1
,num2
,num3
的值。
是否可以制作?
答案 0 :(得分:1)
如果您在插入和更新时需要自动化,则可能需要使用触发器
以下是两个可以根据需要更改表名和字段名的触发器
delimiter //
create trigger cal_average_on_insert before insert on test
for each row
begin
set new.avgnum = (new.num1+new.num2+new.num3)/3 ;
end;//
delimiter ;
delimiter //
create trigger cal_average_on_uodate before update on test
for each row
begin
set new.avgnum = (new.num1+new.num2+new.num3)/3 ;
end;//
delimiter ;
这是mysql cli中的测试用例
mysql> create table test (id int, num1 int, num2 int, num3 int, avgnum float(10,2));
Query OK, 0 rows affected (0.11 sec)
mysql> delimiter //
mysql>
mysql> create trigger cal_average_on_insert before insert on test
-> for each row
-> begin
-> set new.avgnum = (new.num1+new.num2+new.num3)/3 ;
-> end;//
Query OK, 0 rows affected (0.09 sec)
mysql>
mysql> delimiter ;
mysql> delimiter //
mysql>
mysql> create trigger cal_average_on_uodate before update on test
-> for each row
-> begin
-> set new.avgnum = (new.num1+new.num2+new.num3)/3 ;
-> end;//
Query OK, 0 rows affected (0.15 sec)
mysql> insert into test (id,num1,num2,num3) values (1,10,20,30);
Query OK, 1 row affected (0.04 sec)
mysql> insert into test (id,num1,num2,num3) values (2,30,40,50);
Query OK, 1 row affected (0.04 sec)
mysql> select * from test ;
+------+------+------+------+--------+
| id | num1 | num2 | num3 | avgnum |
+------+------+------+------+--------+
| 1 | 10 | 20 | 30 | 20.00 |
| 2 | 30 | 40 | 50 | 40.00 |
+------+------+------+------+--------+
2 rows in set (0.00 sec)
mysql> update test set num1=30, num2=50 where id=1 ;
Query OK, 1 row affected (0.11 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from test ;
+------+------+------+------+--------+
| id | num1 | num2 | num3 | avgnum |
+------+------+------+------+--------+
| 1 | 30 | 50 | 30 | 36.67 |
| 2 | 30 | 40 | 50 | 40.00 |
+------+------+------+------+--------+
2 rows in set (0.00 sec)
答案 1 :(得分:1)
您可以创建一个触发器,如下所示:
CREATE TRIGGER `new_table_BEFORE_INSERT`
BEFORE INSERT ON `new_table`
FOR EACH ROW
set NEW.avgnum = (NEW.num1+NEW.num2+NEW.num3)/3
答案 2 :(得分:0)
Gabor的答案是正确的 - 您似乎需要简单的数学运算,而不是SQL函数SUM
或AVERAGE
:
SELECT (num1 + num2 + num3) / 3 AS avgNum FROM table_name
无论如何,我建议您阅读数据库设计中的3rd normal form并相应地更改表格结构,因为请考虑当您需要时会发生什么:
num4
?OR
子句,而不是简单的JOIN