JSON Insert into a MySQL table or update if exists

后端 未结 1 1305
天涯浪人
天涯浪人 2021-01-28 01:23

This is continuation of Insert into a MySQL table or update if exists, but this time i want to update the json entry in mysql

Below is the schema:

CREATE         


        
相关标签:
1条回答
  • 2021-01-28 01:55

    The following script can be useful for your requirement:

    INSERT INTO `TAG_COUNTER`
      (`account`, `time_id`, `counters`)
    VALUES
      ('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 50}'),
      ('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 50}'),
      ('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 100}'),
      ('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 100}'),
      ('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 100}')
    ON DUPLICATE KEY UPDATE `counters` =
      JSON_SET(`counters`,
               '$."gmail_page_viewed"',
               IFNULL(`counters` ->> '$."gmail_page_viewed"', 0) + 1,
               '$."search_page_viewed"',
               IFNULL(`counters` ->> '$."search_page_viewed"', 0) + 1
      );
    

    See dbfiddle.

    0 讨论(0)
提交回复
热议问题