Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

การสร้าง Stored Generated Columns หลายคอลัมน์ใน MySQL ด้วย CREATE TABLE

สร้าง Stored Generated Columns หลายคอลัมน์ได้โดยเพิ่มคีย์เวิร์ด STORED ตรงท้ายนิพจน์ของแต่ละคอลัมน์

ตัวอย่าง: ตาราง profit1 พร้อม 2 Stored Generated Columns

mysql> CREATE TABLE profit1(
    cost INT,
    price INT,
    profit INT AS (price - cost) STORED,
    price_revised INT AS (price - 2) STORED
  );
Query OK, 0 rows affected (0.36 sec)

mysql> DESCRIBE profit1;
+---------------+---------+------+-----+---------+------------------+
| Field         | Type    | Null | Key | Default | Extra            |
+---------------+---------+------+-----+---------+------------------+
| cost          | int(11) | YES  |     | NULL    |                  |
| price         | int(11) | YES  |     | NULL    |                  |
| profit        | int(11) | YES  |     | NULL    | STORED GENERATED |
| price_revised | int(11) | YES  |     | NULL    | STORED GENERATED |
+---------------+---------+------+-----+---------+------------------+

ทดสอบเพิ่มข้อมูล

mysql> INSERT INTO profit1(cost, price) VALUES(100, 110);
Query OK, 1 row affected (0.09 sec)
mysql> INSERT INTO profit1(cost, price) VALUES(200, 220);
Query OK, 1 row affected (0.09 sec)

mysql> SELECT * FROM profit1;
+------+-------+--------+---------------+
| cost | price | profit | price_revised |
+------+-------+--------+---------------+
| 100  | 110   | 10     | 108           |
| 200  | 220   | 20     | 218           |
+------+-------+--------+---------------+

สรุป: Stored Generated Columns เก็บค่าจริงลงดิสก์ ใช้พื้นที่มากกว่า Virtual แต่คำนวณครั้งเดียวตอน INSERT/UPDATE อ่านเร็วกว่า เหมาะกับนิพจน์คำนวณซับซ้อนหรือข้อมูลที่อ่านบ่อยแต่แก้ไขน้อย