MySQL Shell对关系表中的文档进行操作
在MySQL中,表可以包含传统的关系型数据、JSON值,或者两者都包含。你可以把传统数据和JSON文档结合起来,把文档存储在原生JSON数据类型的列中。
这里使用world_x数据库中的city表进行演示。
city表描述
city表有五个列(或字段)。
mysql> use world_x Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> desc 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 | | +-------------+----------+------+-----+---------+----------------+ 5 rows in set (0.01 sec)
插入记录
要向表的列中插入一个文档,只需按正确的顺序向values()方法传递一个格式良好的JSON文档。在下面的示例中,文档作为要插入Info列的最 终值被传递。
MySQL localhost:33060+ world_x JS > db.city.insert().values(null, "San Francisco", "USA", "California", '{"Population":830000}') Query OK, 1 item affected (0.0104 sec)
查询记录
你可以使用搜索条件进行查询,计算表达式中的文档值。
MySQL localhost:33060+ world_x 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.0078 sec)
删除记录
可以使用搜索条件进行删除,计算表达式中的文档值。
MySQL localhost:33060+ world_x JS > db.city.delete().where("CountryCode = :country and Info->'$.Population' =1830000").bind('country', 'CN') Query OK, 1 item affected (0.0115 sec)