在 MySQL 中向表格新增新列並用相同表格中的其他兩列的資料填充它?


我們首先建立一個表 −

mysql> create table DemoTable
(
   Price int,
   Quantity int
);
Query OK, 0 rows affected (0.71 sec)

使用 insert 命令在表中插入一些記錄 −

mysql> insert into DemoTable values(45,3);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values(90,2);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(440,1);
Query OK, 1 row affected (0.09 sec)

使用 select 語句在表中顯示所有記錄 −

mysql> select *from DemoTable;

這將產生以下輸出 −

+-------+----------+
| Price | Quantity |
+-------+----------+
|    45 |        3 |
|    90 |        2 |
|   440 |        1 |
+-------+----------+
3 rows in set (0.00 sec)

以下是新增新列到表並用 2 個其他列的資料填充的查詢。在這裡,我們添加了新列 TotalAmount,它中的資料是前兩列中的值相乘 −

mysql> select Price,Quantity, Price*Quantity AS TotalAmount from DemoTable;

這將產生以下輸出 −

+-------+----------+-------------+
| Price | Quantity | TotalAmount |
+-------+----------+-------------+
|    45 |        3 |         135 |
|    90 |        2 |         180 |
|   440 |        1 |         440 |
+-------+----------+-------------+
3 rows in set (0.00 sec)

更新於: 2019-09-30

872 次瀏覽

啟動你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.