【问题标题】:How do you insert into an SQLite JSON array without duplicates? (like a set)你如何插入一个没有重复的 SQLite JSON 数组? (像一套)
【发布时间】:2022-08-16 23:36:10
【问题描述】:

鉴于此表:

CREATE TABLE \"carts\" (
    \"id\"    INTEGER NOT NULL,
    \"products\"  TEXT NOT NULL,
    PRIMARY KEY(\"id\" AUTOINCREMENT)
)

products 列包含表示 JSON 数字数组的文本值,如 [12,13,14],如何插入没有重复项的单个项目?

例子

17 添加到[12,13,14] 以提供[12,13,14,17]

13 添加到[12,13,14] 以提供[12,13,14](没有更改因此避免重复)。

    标签: sql json sqlite


    【解决方案1】:
    WITH
        new_product(id, product_id) AS (VALUES (1, 13)),
        new_records AS (
            SELECT carts.id,
                   iif(instr(carts.products, np.product_id), carts.products, json_insert(carts.products, '$[#]', np.product_id)) AS products
            FROM carts, new_product AS np
            WHERE carts.id = np.id
        )
    UPDATE carts SET products = new_records.products
    FROM new_records
    WHERE carts.id = new_records.id;
    

    【讨论】:

    • instr(carts.products, np.product_id) 将为 carts.products = [12,130,14] 和 np.product_id = 13 返回 true
    【解决方案2】:

    我发现这是最简单的方法:

    1. 使用标准函数json_insert 将项目插入到数组中。
      > SELECT json_insert('[12,13,14]','$[#]',13) AS tempArray
      tempArray
      [12,13,14,13]
      
      1. 使用表值函数json_each 将数组拆分为一个临时表。
      > SELECT * FROM (SELECT json_insert('[12,13,14]','$[#]',13) AS tempArray), json_each(tempArray)
      tempArray   key value   type    atom    id  parent  fullkey path
      [12,13,14,13]   0   12  integer 12  1       $[0]    $
      [12,13,14,13]   1   13  integer 13  2       $[1]    $
      [12,13,14,13]   2   14  integer 14  3       $[2]    $
      [12,13,14,13]   3   13  integer 13  4       $[3]    $
      
      1. 只取value 列(因为不需要其他列)。
      > SELECT value FROM (SELECT json_insert('[12,13,14]','$[#]',13) AS tempArray), json_each(tempArray)
      value
      12
      13
      14
      13
      
      1. 使用DISTINCT 删除重复项。
      > SELECT DISTINCT value FROM (SELECT json_insert('[12,13,14]','$[#]',13) AS tempArray), json_each(tempArray)
      value
      12
      13
      14
      
      1. 使用聚合函数json_group_array 将结果组合成一个JSON 数组文本值。
      > SELECT json_group_array(DISTINCT value) FROM (SELECT json_insert('[12,13,14]','$[#]',13) AS tempArray), json_each(tempArray)
      json_group_array(DISTINCT value)
      [12,13,14]
      
      1. 将此语句粘贴到UPDATE 语句中,将示例数组替换为对所需字段的引用。
      UPDATE carts
      SET product = (SELECT json_group_array(DISTINCT value) FROM (SELECT json_insert(carts.product,'$[#]',13) AS tempArray), json_each(tempArray))
      WHERE id = 1
      

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      相关资源
      最近更新 更多