Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Tạo và điền dữ liệu cho cột mới trong bảng MySQL đã có

Tạo bảng:

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

Chèn dữ liệu:

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)

Hiển thị dữ liệu:

mysql> select *from DemoTable;

Kết quả

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

Thêm cột Value3 là generated column (tự động tính: 1 nếu Value1=Value2, 0 nếu khác):

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

Hiển thị lại:

mysql> select *from DemoTable;

Kết quả

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