search
HomeDatabaseMysql TutorialHow to query and modify json data with Mysql

    Query and modify json data

    • Use field->'$.json attribute' to query conditions

    • Use the json_extract function to query, json_extract(field, "$.json attributes")

    • To query based on the json array, use JSON_CONTAINS(field, JSON_OBJECT( 'json attribute', "content")): [{}]Query this form of json array

    • MySQL5.7 or above supports JSON operations and adds a JSON storage type

    • Generally, databases will use JSON type or TEXT type to store JSON type data

    How to query and modify json data with Mysql

    Example

    How to query and modify json data with Mysql

    I did not create the json field format here, but used text to store json.

    Please note: If you want to use the JSON type, the data stored in the column must conform to the JSON format, otherwise an error will occur. 2) The JSON data type has no default value.

    Insert json format data into this column:

    {"age": "28", "pwd": "lisi", "name": "李四"}

    Query

    1,

    select * from `offcn_off_main` where json_extract(json_field,"$.name") = '李四'

    2,

    select * from `offcn_off_main` where json_field->'$.name' = '李四'

    Use explain to see that the index cannot be used.

    So it needs to be modified:

    mysql does not natively support attribute indexing in json columns, but we can indirectly index certain items in json through mysql’s virtual columns. The principle of creating an index for an attribute is to create a virtual column for the attribute in json, and then create an index for the virtual column, thereby indirectly creating an index for the attribute.

    In MySQL 5.7, two types of Generated Column are supported, namely Virtual Generated Column and Stored Generated Column. The former only saves the Generated Column in the data dictionary (metadata of the table) and does not store this column of data. Persist to disk; the latter will persist the Generated Column to disk instead of calculating it each time it is read. Obviously, the latter stores data that can be calculated from existing data, requires more disk space, and has no advantage over Virtual Column----(In fact, I think it still has an advantage, after all, it requires less query calculations. )

    Therefore, in MySQL 5.7, the type of Generated Column is not specified, and the default is Virtual Column.

    If you need Stored Generated Golumn, it may be more appropriate to create an index on Virtual Generated Column. Under normal circumstances, Virtual Generated Column is used, which is also the default method of MySQL.

    The format is as follows:

    fieldname <type> [ GENERATED ALWAYS ] AS ( <expression> ) [ VIRTUAL|STORED ] [ UNIQUE [KEY] ] [ [PRIMARY] KEY ] [ NOT NULL ] [ COMMENT <text> ]

    So here I am:

    ALTER TABLE &#39;off_main&#39; `names_virtual` VARCHAR(20) GENERATED ALWAYS AS (`json_field` ->> &#39;$.name&#39;) not null;

    Please note: You can use the "»" operator to reference keys in JSON fields (KEY). In this example, the virtual field names_virtual has been defined as non-nullable. In actual work, it must be determined based on specific circumstances. Because JSON itself is a weakly structured data object. In other words, its structure is not fixed.

    Add an index to the virtual field:

    CREATE INDEX `names` ON `off_main`(`names_virtual`);

    Note that if the virtual field is not added when the table is created, but added later, when adding the index, if the virtual field in some rows is null, But if it is set to not be null, then the index cannot be created successfully, and the prompt column can not be null.

    After adding the index, please explain and you will see that the index is used, and the value of the virtual field will change with the The properties of the json field change automatically when modified.

    Let’s take a look at the modification

    update off_main set json_field = json_set(json_field,&#39;$.phone&#39;, &#39;132&#39;) WHERE id = 45 
    //同时修改多个
    UPDATE offcn_off_main set json_field = json_set(json_field,&#39;$.name&#39;,456,&#39;$.age&#39;,&#39;bbb&#39;) WHERE id = 45

    The json_set() method that exists will be overwritten, and the one that does not exist will be added.

    Delete

    UPDATE offcn_off_main set json_field = json_remove(json_field,&#39;$.pwd&#39;,&#39;$.phone&#39;) WHERE id = 45

    Insert

    UPDATE offcn_off_main set json_field = json_insert(json_field,&#39;$.pwd&#39;,&#39;111&#39;) WHERE id = 45

    The difference between insert and update is that if the insert does not exist, it will be added, and if it exists, it will not be overwritten.

    Mysql processes json Data

    1. If the amount of data is small, copy the json data directly to the json field of mysql. If the data is too large, you can parse the json data through java and other background forms, and then write it to the database.

    Query operation

    select *,json->&#39;$.features[0].geometry.rings&#39; as rings from JSON;

    Read part of the data from one table and store it in another table (one piece of data)

    insert into DT_village(name, border) SELECT
      json->&#39;$.features[0].attributes.CJQYMC&#39;,json->&#39;$.features[0].geometry.rings&#39;
    from JSON;

    Read json data and write it to the database (at this time The method is executed in the form of a defined function, and the amount can be defined)

    #清空数据库
    TRUNCATE table DT_village;
     
    #定义存储过程
    delimiter //
    DROP PROCEDURE IF EXISTS insert_test_val;
    ##num_limit 要插入数据的数量,rand_limit 最大随机的数值
    CREATE PROCEDURE insert_test_val()
      BEGIN
     
        DECLARE i int default 0;
        DECLARE a,b varchar(5000);
     
        WHILE i<10 do
          set a=CONCAT(&#39;$.features[&#39;,i,&#39;].attributes.CJQYMC&#39;);
          set b=CONCAT(&#39;$.features[&#39;,i,&#39;].geometry.rings&#39;);
          insert into DT_village(name, border) select
                  #json->&#39;$.features[0].attributes.CJQYMC&#39;,json->&#39;$.features[0].geometry.rings&#39;
                                                     # (json->a),(json->b)
       json_extract(json,a),json_extract(json,b)
          from JSON;
          set i = i + 1;
     
        END WHILE;
     
      END
    //
     
    #调用存储过程
    call insert_test_val();

    Call the cursor to obtain a row in the jsosn data, and perform the insertion operation

    delimiter //
    drop procedure if exists StatisticStore;
    CREATE PROCEDURE StatisticStore()
      BEGIN
        #创建接收游标数据的变量
        declare j json;#存储json数据
        DECLARE i int default 0; #创建总数变量,记录执行次数,控制循环
        DECLARE a,b,c varchar(5000);#定义json数组中的某个数据的键值
     
        #创建结束标志变量
        declare done int default false;
        #创建游标
        declare cur cursor for select json from JSON where name = &#39;1&#39;;
        #指定游标循环结束时的返回值
        declare continue HANDLER for not found set done = true;
        #设置初始值
        set a=CONCAT(&#39;$.features[&#39;,i,&#39;].attributes.XZQDM&#39;);
        set b=CONCAT(&#39;$.features[&#39;,i,&#39;].attributes.XZQMC&#39;);
        set c=CONCAT(&#39;$.features[&#39;,i,&#39;]&#39;);
        #打开游标
        open cur;
        #开始循环游标里的数据
        read_loop:loop
          #根据游标当前指向的一条数据
          fetch cur into j;
          #判断游标的循环是否结束
          if done then
            leave read_loop;#跳出游标循环
          end if;
          #这里可以做任意你想做的操作
          WHILE i<11 do
            insert into dt_border(xzq_code,name,border) select
                                                               json_extract(j,a),json_extract(j,b),json_extract(j,c)
            from JSON;
            set i = i + 1;
          END WHILE;
          #结束游标循环
        end loop;
        #关闭游标
        close cur;
     
        #输出结果
        select j,i;
      END;
    #调用存储过程
    call StatisticStore();

    The above is the detailed content of How to query and modify json data with Mysql. For more information, please follow other related articles on the PHP Chinese website!

    Statement
    This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
    When should you use a composite index versus multiple single-column indexes?When should you use a composite index versus multiple single-column indexes?Apr 11, 2025 am 12:06 AM

    In database optimization, indexing strategies should be selected according to query requirements: 1. When the query involves multiple columns and the order of conditions is fixed, use composite indexes; 2. When the query involves multiple columns but the order of conditions is not fixed, use multiple single-column indexes. Composite indexes are suitable for optimizing multi-column queries, while single-column indexes are suitable for single-column queries.

    How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)How to identify and optimize slow queries in MySQL? (slow query log, performance_schema)Apr 10, 2025 am 09:36 AM

    To optimize MySQL slow query, slowquerylog and performance_schema need to be used: 1. Enable slowquerylog and set thresholds to record slow query; 2. Use performance_schema to analyze query execution details, find out performance bottlenecks and optimize.

    MySQL and SQL: Essential Skills for DevelopersMySQL and SQL: Essential Skills for DevelopersApr 10, 2025 am 09:30 AM

    MySQL and SQL are essential skills for developers. 1.MySQL is an open source relational database management system, and SQL is the standard language used to manage and operate databases. 2.MySQL supports multiple storage engines through efficient data storage and retrieval functions, and SQL completes complex data operations through simple statements. 3. Examples of usage include basic queries and advanced queries, such as filtering and sorting by condition. 4. Common errors include syntax errors and performance issues, which can be optimized by checking SQL statements and using EXPLAIN commands. 5. Performance optimization techniques include using indexes, avoiding full table scanning, optimizing JOIN operations and improving code readability.

    Describe MySQL asynchronous master-slave replication process.Describe MySQL asynchronous master-slave replication process.Apr 10, 2025 am 09:30 AM

    MySQL asynchronous master-slave replication enables data synchronization through binlog, improving read performance and high availability. 1) The master server record changes to binlog; 2) The slave server reads binlog through I/O threads; 3) The server SQL thread applies binlog to synchronize data.

    MySQL: Simple Concepts for Easy LearningMySQL: Simple Concepts for Easy LearningApr 10, 2025 am 09:29 AM

    MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

    MySQL: A User-Friendly Introduction to DatabasesMySQL: A User-Friendly Introduction to DatabasesApr 10, 2025 am 09:27 AM

    The installation and basic operations of MySQL include: 1. Download and install MySQL, set the root user password; 2. Use SQL commands to create databases and tables, such as CREATEDATABASE and CREATETABLE; 3. Execute CRUD operations, use INSERT, SELECT, UPDATE, DELETE commands; 4. Create indexes and stored procedures to optimize performance and implement complex logic. With these steps, you can build and manage MySQL databases from scratch.

    How does the InnoDB Buffer Pool work and why is it crucial for performance?How does the InnoDB Buffer Pool work and why is it crucial for performance?Apr 09, 2025 am 12:12 AM

    InnoDBBufferPool improves the performance of MySQL databases by loading data and index pages into memory. 1) The data page is loaded into the BufferPool to reduce disk I/O. 2) Dirty pages are marked and refreshed to disk regularly. 3) LRU algorithm management data page elimination. 4) The read-out mechanism loads the possible data pages in advance.

    MySQL: The Ease of Data Management for BeginnersMySQL: The Ease of Data Management for BeginnersApr 09, 2025 am 12:07 AM

    MySQL is suitable for beginners because it is simple to install, powerful and easy to manage data. 1. Simple installation and configuration, suitable for a variety of operating systems. 2. Support basic operations such as creating databases and tables, inserting, querying, updating and deleting data. 3. Provide advanced functions such as JOIN operations and subqueries. 4. Performance can be improved through indexing, query optimization and table partitioning. 5. Support backup, recovery and security measures to ensure data security and consistency.

    See all articles

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    AI Hentai Generator

    AI Hentai Generator

    Generate AI Hentai for free.

    Hot Article

    R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
    WWE 2K25: How To Unlock Everything In MyRise
    3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

    Hot Tools

    DVWA

    DVWA

    Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

    Safe Exam Browser

    Safe Exam Browser

    Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    MantisBT

    MantisBT

    Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.