美文网首页
MySQL JSON

MySQL JSON

作者: Muscleape | 来源:发表于2019-11-05 16:31 被阅读0次

    JSON类型,需要MySQL版本最低5.7.8
    下文中的部分函数,5.7.8版本不支持,以下操作在5.7.20版本中验证通过

    SELECT version();
    SELECT * FROM `json_table`;
    -- 新增数据
    INSERT INTO `json_table` (id, json_field) VALUES (1,'{"operation_line_one":1,"operation_line_two":2}');
    INSERT INTO `json_table` (id, json_field) VALUES (2,'{"operation_line_one":3,"operation_line_two":4}');
    INSERT INTO `json_table` (id, json_field) VALUES (3,'{"operation_line_one":1,"operation_line_two":4}');
    INSERT INTO `json_table` (id, json_field) VALUES (4,'{"operation_line_one":3,"operation_line_two":2}');
    INSERT INTO `json_table` (id, json_field) VALUES (5,JSON_OBJECT("operation_line_one", 1, "operation_line_two",3));
    -- json_contains的第二个参数必须是字符串,无论数据是什么类型
    SELECT * FROM `json_table` WHERE json_contains(json_field,'1','$.operation_line_one');
    SELECT * FROM `json_table` WHERE json_contains(json_field,'1','$.operation_line_one');
    -- 参数类型必须统一,库中字段是int类型的,字段必须是int类型
    SELECT * FROM `json_table` WHERE `json_field` -> '$.operation_line_one' = 1;
    SELECT * FROM `json_table` WHERE `json_field` -> '$.operation_line_one' = '1';
    SELECT * FROM `json_table` WHERE `json_field` ->> '$.operation_line_one' = 1;
    SELECT * FROM `json_table` WHERE `json_field` ->> '$.operation_line_one' = '1';
    SELECT * FROM `json_table` WHERE `json_field` -> '$.operation_line_one' = 1 AND `json_field` ->> '$.operation_line_two' = '2';
    -- JSON_INSERT()插入新值,但不会覆盖已经存在的值
    UPDATE `json_table` SET `json_field` = json_insert(`json_field`,'$.operation_line_one_name','北京-保定');
    UPDATE `json_table` SET `json_field` = json_insert(`json_field`,'$.operation_line_two_name','');
    -- JSON_SET() 插入新值,并覆盖已经存在的值
    -- JSON_REPLACE() 只替换存在的值
    -- JSON_REMOVE() 删除 JSON 元素
    

    相关文章

      网友评论

          本文标题:MySQL JSON

          本文链接:https://www.haomeiwen.com/subject/pkhebctx.html