如何在不使用聚合函数的情况下添加 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)
广告