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-py> db.city.insert().values(
None, "San Francisco", "USA", "California", '{"Population":830000}')
您可以使用在運算式中評估文件值的搜尋條件來發出查詢。
mysql-py> 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 資料類型」 以取得資料類型的詳細說明。