如何提取和展平 MySQL 8 中 JSON 对象内部的数组?

How to extract and flatten and array that is inside of JSON objects in MySQL 8?

给定一些 json 文档,如下所示:

{
   "_id":"00006073",
    "subscribersIds":[
      170968,
      225647
   ]
}
-----------------------------------
{
   "_id":"00006072",
   "subscribersIds":[
      170968
   ]
}
--------------------------------
{
   "_id":"00006074,
   "subscribersIds":[
      228195,
      225647
   ]
}

你知道我怎样才能得到 subscribersIds 的列表,而不重复吗? 结果应该是这样的 170968, 225647, 228195,因为我需要使用此查询的结果作为另一个查询的条件。

对于 Couchebase 有执行此操作的“UNNEST”命令,但是我在 MySQL 8 中找不到正确的方法,因为 SELECT DISTINCT doc ->> '$.subscribersIds[*]' FROM customers 将 return [170968,225647],[170968],[228195,225647]

提前致谢!

mysql> select * from mytable;
+----------+------------------+
| _id      | subscriberIds    |
+----------+------------------+
| 00006072 | [170968]         |
| 00006073 | [170968, 225647] |
| 00006074 | [228195, 225647] |
+----------+------------------+

mysql> select j.subscriberId from mytable, 
  json_table(mytable.subscriberIds, '$[*]' columns (subscriberId int path '$')) j;
+--------------+
| subscriberId |
+--------------+
|       170968 |
|       170968 |
|       225647 |
|       228195 |
|       225647 |
+--------------+

mysql> select distinct j.subscriberId from mytable,
  json_table(mytable.subscriberIds, '$[*]' columns (subscriberId int path '$')) j;
+--------------+
| subscriberId |
+--------------+
|       170968 |
|       225647 |
|       228195 |
+--------------+

这是一个相当复杂的查询,每次您想要获取一组不同的 subscriberId 时都要编写。

如果您根本不使用 JSON,而是以规范化的方式存储 id,一秒钟内每行一个 table。

,会容易得多
mysql> create table mySubscribers (_id char(8), subscriberId int, primary key (_id, subscriberId));

mysql> insert into mySubscribers (_id, subscriberId) select _id, subscriberId from mytable, json_table(subscriberIds, '$[*]' columns (subscriberId int path '$')) j;
Records: 5  Duplicates: 0  Warnings: 0

mysql> select * from mySubscribers;
+----------+--------------+
| _id      | subscriberId |
+----------+--------------+
| 00006072 |       170968 |
| 00006073 |       170968 |
| 00006073 |       225647 |
| 00006074 |       225647 |
| 00006074 |       228195 |
+----------+--------------+

mysql> select distinct subscriberId from mySubscribers;
+--------------+
| subscriberId |
+--------------+
|       170968 |
|       225647 |
|       228195 |
+--------------+