MySQL 如何添加列值而不使用聚合函数
您可以添加列值而不使用聚合函数如sum()。语法如下 −
SELECT *,(yourColumnName1+yourColumnName2+yourColumnName3,… N) as
anyVariableName from yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询语句如下 −
mysql> create table AddingColumnDemo
-> (
-> StudentId int,
-> StudentName varchar(20),
-> MathMarks int,
-> PhysicsMarks int,
-> ChemistryMarks int
-> );
Query OK, 0 rows affected (0.82 sec)
使用insert命令在表中插入记录。查询语句如下 −
mysql> insert into AddingColumnDemo values(1,'John',35,45,76);
Query OK, 1 row affected (0.25 sec)
mysql> insert into AddingColumnDemo values(2,'Bob',67,76,88);
Query OK, 1 row affected (0.19 sec)
mysql> insert into AddingColumnDemo values(3,'Carol',45,56,43);
Query OK, 1 row affected (0.16 sec)
mysql> insert into AddingColumnDemo values(4,'Mike',82,75,71);
Query OK, 1 row affected (0.21 sec)
mysql> insert into AddingColumnDemo values(5,'Sam',92,89,88);
Query OK, 1 row affected (0.23 sec)
使用select语句显示表中的所有记录−
mysql> select *from AddingColumnDemo;
以下是显示表的记录的输出−
+-----------+-------------+-----------+--------------+----------------+
| StudentId | StudentName | MathMarks | PhysicsMarks | ChemistryMarks |
+-----------+-------------+-----------+--------------+----------------+
| 1| John | 35 | 45 |76 |
| 2| Bob | 67 | 76 |88 |
| 3| Carol | 45 | 56 |43 |
| 4| Mike | 82 | 75 |71 |
| 5| Sam | 92 | 89 |88 |
+-----------+-------------+------------+-------------+----------------+
5 rows in set (0.00 sec)
现在让我们实现在MySQL中添加列值的查询 −
mysql> select *,(MathMarks+PhysicsMarks+ChemistryMarks) as TotalResult from AddingColumnDemo;
以下是显示TotalResult列中列值总和的输出−
+-----------+-------------+-----------+--------------+----------------+-------------+
| StudentId | StudentName | MathMarks | PhysicsMarks | ChemistryMarks | TotalResult |
+-----------+-------------+-----------+--------------+----------------+-------------+
| 1| John | 35 | 45 | 76 |156 |
| 2| Bob | 67 | 76 | 88 |231 |
| 3| Carol | 45 | 56 | 43 |144 |
| 4| Mike | 82 | 75 | 71 |228 |
| 5| Sam | 92 | 89 | 88 |269 |
+-----------+-------------+-----------+--------------+----------------+-------------+
5 rows in set (0.00 sec)
阅读更多:MySQL 教程