MySQL 8.4 版本說明
在 MySQL 中,表格可以包含傳統的關聯式資料、JSON 值或兩者。您可以將傳統資料與 JSON 文件結合,方法是將文件儲存在具有原生 JSON
資料類型的資料行中。
本節中的範例使用 world_x
結構描述中的 city 表格。
city 表格有五個資料行 (或欄位)。
+---------------+------------+-------+-------+---------+------------------+ | Field | Type | Null | Key | Default | Extra | +---------------+------------+-------+-------+---------+------------------+ | ID | int(11) | NO | PRI | null | auto_increment | | Name | char(35) | NO | | | | | CountryCode | char(3) | NO | | | | | District | char(20) | NO | | | | | Info | json | YES | | null | | +---------------+------------+-------+-------+---------+------------------+
若要將文件插入表格的資料行,請將格式正確的 JSON 文件以正確的順序傳遞至 values()
方法。在下列範例中,會將文件當作要插入 Info 資料行的最終值傳遞。
mysql-js> db.city.insert().values(
None, "San Francisco", "USA", "California", '{"Population":830000}')
您可以使用搜尋條件發出查詢,該搜尋條件會評估運算式中的文件值。
mysql-js> db.city.select(["ID", "Name", "CountryCode", "District", "Info"]).where(
"CountryCode = :country and Info->'$.Population' > 1000000").bind(
'country', 'USA')
+------+----------------+-------------+----------------+-----------------------------+
| ID | Name | CountryCode | District | Info |
+------+----------------+-------------+----------------+-----------------------------+
| 3793 | New York | USA | New York | {"Population": 8008278} |
| 3794 | Los Angeles | USA | California | {"Population": 3694820} |
| 3795 | Chicago | USA | Illinois | {"Population": 2896016} |
| 3796 | Houston | USA | Texas | {"Population": 1953631} |
| 3797 | Philadelphia | USA | Pennsylvania | {"Population": 1517550} |
| 3798 | Phoenix | USA | Arizona | {"Population": 1321045} |
| 3799 | San Diego | USA | California | {"Population": 1223400} |
| 3800 | Dallas | USA | Texas | {"Population": 1188580} |
| 3801 | San Antonio | USA | Texas | {"Population": 1144646} |
+------+----------------+-------------+----------------+-----------------------------+
9 rows in set (0.01 sec)
如需詳細資訊,請參閱使用關聯式表格和文件。
如需資料類型的詳細說明,請參閱第 13.5 節,「JSON 資料類型」。