如何在不使用聚合函数的情况下在 MySQL 中添加列值?
mysqlmysqli database更新于 2024/3/15 0:46:00
您可以添加列值而不使用聚合函数(如 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;
The following is the output displaying the records of the table −
+-----------+-------------+-----------+--------------+----------------+ | 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)