การสร้างสตริงรูปแบบ JSON ด้วย CONCAT() ใน MySQL
ก่อน MySQL 5.7 (ที่มี JSON data type และฟังก์ชัน JSON_OBJECT) การสร้าง JSON string ต้องใช้ CONCAT() รวมค่าต่างๆ เอง
สร้างตารางและข้อมูล (คอลัมน์ว่างเปล่า)
mysql> create table DemoTable1373 (
-> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> StudentDetails text
-> );
Query OK, 0 rows affected (0.86 sec)
mysql> insert into DemoTable1373 values();
mysql> insert into DemoTable1373 values();
mysql> insert into DemoTable1373 values();
ข้อมูลก่อนอัปเดต
+-----------+----------------+ | StudentId | StudentDetails | +-----------+----------------+ | 1 | NULL | | 2 | NULL | | 3 | NULL | +-----------+----------------+
คำสั่ง UPDATE สร้าง JSON string ด้วย CONCAT
mysql> update DemoTable1373
-> set StudentDetails = concat(
-> "{",
-> "StudentName:", " John ", ",",
-> "StudentAge:", 21, ",",
-> "StudentCountryName: ", "US", "}"
-> );
Query OK, 3 rows affected (0.14 sec)
ข้อมูลหลังอัปเดต
+-----------+---------------------------------------------------------------+
| StudentId | StudentDetails |
+-----------+---------------------------------------------------------------+
| 1 | {StudentName: John , StudentAge:21, StudentCountryName: US} |
| 2 | {StudentName: John , StudentAge:21, StudentCountryName: US} |
| 3 | {StudentName: John , StudentAge:21, StudentCountryName: US} |
+-----------+---------------------------------------------------------------+
วิธีที่ดีกว่าใน MySQL 5.7+ : ใช้ JSON_OBJECT
UPDATE DemoTable1373 SET StudentDetails = JSON_OBJECT( 'StudentName', 'John', 'StudentAge', 21, 'StudentCountryName', 'US' );
ผลลัพธ์: {"StudentName": "John", "StudentAge": 21, "StudentCountryName": "US"} (JSON ถูกต้อง มี double quotes, escape อัตโนมัติ)
ฟังก์ชัน JSON อื่นๆ ที่มีประโยชน์
| ฟังก์ชัน | คำอธิบาย |
|---|---|
JSON_ARRAY() | สร้าง JSON array |
JSON_EXTRACT() | ดึงค่าจาก JSON (-> operator) |
JSON_SET() | อัปเดตค่าใน JSON |
JSON_REMOVE() | ลบ key จาก JSON |
JSON_VALID() | ตรวจสอบ JSON ถูกต้อง |
ข้อควรระวัง: วิธี CONCAT แบบดิบไม่ escape ค่าพิเศษ (quotes, backslash, newline) อาจทำให้ JSON แพ้หรือ inject ได้ ควรใช้ JSON_OBJECT/JSON_ARRAY เสมอใน production