如何在已建立的 MySQL 表中建立和填充新列?


讓我們首先建立一個表:

mysql> create table DemoTable
   -> (
   -> Value1 int,
   -> Value2 int
   -> );
Query OK, 0 rows affected (0.77 sec)

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

mysql> insert into DemoTable values(10,10);
Query OK, 1 row affected (0.19 sec)

mysql> insert into DemoTable values(20,30);
Query OK, 1 row affected (0.24 sec)

使用 select 語句顯示錶中的所有記錄:

mysql> select *from DemoTable;

輸出

這將產生以下輸出:

+--------+--------+
| Value1 | Value2 |
+--------+--------+
|     10 |   10   |
|     20 |   30   |
+--------+--------+
2 rows in set (0.00 sec)

以下是建立和填充 MySQL 表中第三列的查詢。此處,布林值在整數上下文中被視為整數,即 0 代表 false,1 代表 true。

我們在這裡使用了生成的列:

mysql> alter table DemoTable add Value3 int generated always as (Value1 = Value2);
Query OK, 0 rows affected (0.51 sec)
Records: 0  Duplicates: 0  Warnings: 0

讓我們再次顯示錶中的所有記錄:

mysql> select *from DemoTable;

輸出

這將產生以下輸出:

+--------+--------+--------+
| Value1 | Value2 | Value3 |
+--------+--------+--------+
|     10 |   10   | 1      |
|     20 |   30   | 0      |
+--------+--------+--------+
2 rows in set (0.00 sec)

更新於:2020-06-30

1K+ 次瀏覽

啟動你的 職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.