我正在尝试查询包含对象数组的 Mysql json 列。我想要在对象中满足条件的数组的长度
JSON 数组示例:
[
{"userId": 100, "type": 1, "status": 1},
{"userId": 101, "type": 2, "status": 1},
]
Run Code Online (Sandbox Code Playgroud)
当前查询:
SELECT IFNULL(JSON_LENGTH(json_users), 0) AS my_count, post_id
FROM posts WHERE post_id = 6421028173277829027
AND json_contains(json_users, '{"type" : 1, "status": 1}');
Run Code Online (Sandbox Code Playgroud)
这将返回以下所需的
+------------+---------------------+
| my_count | post_id |
+------------+---------------------+
| 1 | 6421028173277829027 |
+------------+---------------------+
Run Code Online (Sandbox Code Playgroud)
但是,如果我将查询 where param 'type' 更改为 3
SELECT IFNULL(JSON_LENGTH(json_users), 0) AS my_count, post_id
FROM posts WHERE post_id = 6421028173277829027
AND json_contains(json_users, '{"type" : 3, "status": 1}');
Run Code Online (Sandbox Code Playgroud)
我得到一个空集。但我试图得到以下内容:
+------------+---------------------+
| my_count | post_id |
+------------+---------------------+
| 0 | 6421028173277829027 |
+------------+---------------------+
Run Code Online (Sandbox Code Playgroud)
我假设我必须更改 where 子句并以某种方式检查以下内容:
IFNULL(JSON_LENGTH(## json_users ##), 0)
Run Code Online (Sandbox Code Playgroud)
但我不知道从哪里开始
编辑:
以下查询返回对象的路径数组,以便我可以使用 JSON_LENGTH 获取计数:
SELECT JSON_LENGTH(IFNULL(JSON_SEARCH(json_users->>'$[*].type', 'all', 1), JSON_ARRAY())) AS my_count
FROM posts WHERE post_id = 6421028173277829027;
Run Code Online (Sandbox Code Playgroud)
小智 6
你试过了吗
SELECT JSON_LENGTH(JSON_EXTRACT(json_users, "$.type")) FROM posts
Run Code Online (Sandbox Code Playgroud)
我知道有一个错误,如果json_users为空,则不会返回任何内容。
| 归档时间: |
|
| 查看次数: |
7420 次 |
| 最近记录: |