MySQL 5.7+ รองรับ Native JSON Data Type มี Validation, Indexing (Generated Column), และ Functions ครบครัน
สร้างตารางมี JSON Column
mysql> CREATE TABLE JsonAsMySQLDemo (
-> id INT,
-> name VARCHAR(100),
-> PageDemo JSON,
-> eventInfo JSON
-> );
Insert JSON Data
mysql> INSERT INTO JsonAsMySQLDemo VALUES
-> (1, 'John', '{"Page1":"/"}', '{"OperatingSystem":"Windows"}'),
-> (2, 'Bob', '{"Page2":"/"}', '{"OperatingSystem":"Solaris"}');
Query JSON Data
mysql> SELECT * FROM JsonAsMySQLDemo;
+------+------+----------------+--------------------------------+
| id | name | PageDemo | eventInfo |
+------+------+----------------+--------------------------------+
| 1 | John | {"Page1": "/"} | {"OperatingSystem": "Windows"} |
| 2 | Bob | {"Page2": "/"} | {"OperatingSystem": "Solaris"} |
+------+------+----------------+--------------------------------+
JSON Functions ที่น่าสนใจ
| Function | คำอธิบาย |
|---|---|
JSON_EXTRACT(col, '$.path') / col->'$.path' | ดึงค่าจาก JSON |
JSON_UNQUOTE(JSON_EXTRACT(...)) / col->>'$.path' | ดึงค่าเป็น Text (ไม่มี Quote) |
JSON_SET(col, '$.path', value) | อัปเดต/เพิ่มค่าใน JSON |
JSON_CONTAINS(col, 'value', '$.path') | เช็คว่ามีค่าใน JSON |
JSON_ARRAYAGG(), JSON_OBJECTAGG() | Aggregate สร้าง JSON Array/Object |
Indexing JSON: ไม่ Index JSON Column โดยตรงได้ ต้องสร้าง Generated Column แล้ว Index Column นั้น (MySQL 5.7+) หรือใช้ Multi-valued Index (MySQL 8.0.17+)