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

Tạo cột mới chứa hiệu hai cột trong MySQL

Truy vấn SELECT có thể tính toán cột mới trực tiếp bằng phép trừ hai cột hiện có.

Ví dụ

Tạo bảng LowValue, HighValue:

mysql> create table DemoTable ( 
    Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    LowValue int, 
    HighValue int 
); 
Query OK, 0 rows affected (0.62 sec)

Dữ liệu: (100,200), (300,700), (1000,2000)

Truy vấn có cột Difference

mysql> select tbl.Id,tbl.LowValue,tbl.HighValue, HighValue-LowValue AS DifferenceBetweenTwoColumns from DemoTable tbl;
+----+----------+-----------+-----------------------------+
| Id | LowValue | HighValue | DifferenceBetweenTwoColumns |
+----+----------+-----------+-----------------------------+
| 1  | 100      | 200       | 100                         |
| 2  | 300      | 700       | 400                         |
| 3  | 1000     | 2000      | 1000                        |
+----+----------+-----------+-----------------------------+

Lưu ý: Cột tính toán (computed column) chỉ tồn tại trong kết quả truy vấn. Muốn lưu vĩnh viễn, dùng:

  • ALTER TABLE ... ADD COLUMN Difference INT GENERATED ALWAYS AS (HighValue-LowValue) STORED (MySQL 5.7+)
  • Hoặc trigger UPDATE/INSERT