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

Cập nhật cột MySQL với định dạng JSON bằng hàm CONCAT

Tạo bảng có cột text

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();

Dữ liệu ban đầu (NULL)

mysql> SELECT * FROM DemoTable1373;
+-----------+----------------+
| StudentId | StudentDetails |
+-----------+----------------+
| 1         | NULL           |
| 2         | NULL           |
| 3         | NULL           |
+-----------+----------------+

Cập nhật: Tạo chuỗi JSON thủ công bằng CONCAT

mysql> UPDATE DemoTable1373
    -> SET StudentDetails = CONCAT('{',
    ->   '"StudentName":"John",',
    ->   '"StudentAge":21,',
    ->   '"StudentCountryName":"US"',
    ->   '}');
Query OK, 3 rows affected (0.14 sec)

Kết quả

mysql> SELECT * FROM DemoTable1373;
+-----------+---------------------------------------------------+
| StudentId | StudentDetails                                    |
+-----------+---------------------------------------------------+
| 1         | {"StudentName":"John","StudentAge":21,"StudentCountryName":"US"} |
| 2         | {"StudentName":"John","StudentAge":21,"StudentCountryName":"US"} |
| 3         | {"StudentName":"John","StudentAge":21,"StudentCountryName":"US"} |
+-----------+---------------------------------------------------+

Lưu ý: MySQL 5.7+ hỗ trợ kiểu dữ liệu JSON và hàm JSON_OBJECT(), JSON_ARRAY() tạo JSON chuẩn, an toàn hơn so với ghép chuỗi thủ công.