【问题标题】:MySQL turn JSON_ARRAY of ids into JSON_ARRAY of values [MySQL 8]MySQL 将 ID 的 JSON_ARRAY 转换为值的 JSON_ARRAY [MySQL 8]
【发布时间】:2021-03-18 02:05:27
【问题描述】:

我有一个 JSON_ARRAY 的 ID,格式为 [1,3,...]。每个值都代表另一个表中的值的 id。

Table: pets
id | value
 1 | cat
 2 | dog
 3 | hamster

Table: pet_owner
id | pets_array
 1 | [1, 3]
 2 | [2]
 3 | []

我查询pet_owners时想要得到的是以下结果:

Table: pet_owner
id | pets_array
 1 | ["cat", "hamster"]
 2 | ["dog"]
 3 | []

如何对每个数组元素运行子选择以获取其值?

【问题讨论】:

    标签: mysql sql arrays json mysql-8.0


    【解决方案1】:

    随着 JSON 的发展,处理起来总是很痛苦

    当你还需要所有没有宠物的时候,你必须离开加入所有者表

    CREATE TABLE pet_owner (
      `id` INTEGER,
      `pets_array` JSON
    );
    
    INSERT INTO pet_owner
      (`id`, `pets_array`)
    VALUES
      ('1', '[1, 3]'),
      ('2', '[2]'),
      ('3', '[]');
      
    
    
    
    CREATE TABLE pets (
      `id` INTEGER,
      `value` VARCHAR(7)
    );
    
    INSERT INTO pets
      (`id`, `value`)
    VALUES
      ('1', 'cat'),
      ('2', 'dog'),
      ('3', 'hamster');
    
    SELECT
    t1.id,
    JSON_ARRAYAGG(
      p.`value`
    ) AS pets_array 
    FROM(
    SELECT * 
    FROM pet_owner ,
    JSON_TABLE(
          pet_owner.pets_array , "$[*]" 
          COLUMNS(IDs int PATH "$" NULL ON ERROR DEFAULT '0' ON EMPTY )
    ) AS J_LINK ) t1
    LEFT JOIN pets p ON p.id =t1.IDs
    GROUP BY 
    t1.id
    ;
    
    编号 |宠物数组 -: | :----------------- 1 | [“猫”,“仓鼠”] 2 | [“狗”]

    db小提琴here

    规范化的表格可以让您将数据转换为可用的列。

    【讨论】:

      【解决方案2】:

      你可以加入json_contains(),然后重新聚合:

      select po.id, json_arrayagg(p.value) as owners
      from pet_owner po
      left join pets p on json_contains(po.pets_array, cast(p.id as char))
      group by po.id
      

      请注意,与大多数(如果不是全部!)其他数据库不同,MySQL 不保证 json_arrayagg() 生成的数组中元素的顺序:这只是我们在当前版本中必须接受的事实。

      【讨论】:

        猜你喜欢
        • 2020-05-19
        • 2021-04-15
        • 2020-04-18
        • 1970-01-01
        • 2020-11-13
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 2021-02-11
        相关资源
        最近更新 更多