如何在不使用聚合函式的情況下新增 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)
廣告