MySQL 9.0 發行說明
在 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 資料類型」。