简体   繁体   English

如何将 json 数组和 append 插入 SQL 的列中

[英]How to insert and append a json array into a column in SQL

I've followed a few tuts online and I've come across a simple approach but its throwing some errors.我在网上关注了一些 tuts,我遇到了一个简单的方法,但它会抛出一些错误。

I have 2 columns in my table.我的表中有 2 列。

  • user_id (INT) user_id (INT)
  • purchased_products (JSON)购买的产品 (JSON)

I simply want to keep an array of purchased product IDs in the purchased_products column in json format ["32","33","86","10"].我只是想在 json 格式 ["32","33","86","10"] 的购买产品列中保留一系列购买的产品 ID。

My query, looking to append 34 onto the array:我的查询,寻找 append 34 到阵列上:

UPDATE customers_purchased_products 
SET 
purchased_products = JSON_MODIFY(purchased_products,
        'append $.purchased_products',
        '34')
WHERE
user_id = 12345

Is this valid SQL?这是有效的 SQL 吗?

Im also getting an error: Error Code: 1305. FUNCTION database_name.JSON_MODIFY does not exist我也收到错误: Error Code: 1305. FUNCTION database_name.JSON_MODIFY does not exist

So i ended up simply needing to insert the first instance as just json formatted text.所以我最终只需要插入第一个实例作为 json 格式化文本。 The remaining products could be added to the newly created array using a different function.剩余的产品可以使用不同的 function 添加到新创建的阵列中。

-- Insert a new row into the purchased products table
INSERT INTO purchased_products (
    user_id, -- INT
    purchased_products -- JSON
)

-- 1) The user ID (primary key)
-- 2) Formatted json array with the first purchased product ID
VALUES ( 12345, '["35"]' )

-- If the user id already exists, append the existing array with the product ID
ON DUPLICATE KEY UPDATE 

    -- JSON_ARRAY_INSERT(existing purchases array, index, product_id)
    purchased_products = JSON_ARRAY_INSERT(purchased_products, '$[0]', "35") 

Whilst there may be multiple items per order, a single statement for each item will cover every instance.虽然每个订单可能有多个项目,但每个项目的单个声明将涵盖每个实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM