如何在不使用聚合函数的情况下在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 -> );
使用insert命令在表中插入记录。查询如下-
mysql> insert into AddingColumnDemo values(1,'John',35,45,76); mysql> insert into AddingColumnDemo values(2,'Bob',67,76,88); mysql> insert into AddingColumnDemo values(3,'Carol',45,56,43); mysql> insert into AddingColumnDemo values(4,'Mike',82,75,71); mysql> insert into AddingColumnDemo values(5,'Sam',92,89,88);
使用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)