mysql - 在 MySQL 的 JSON 数组字段中查找匹配项

标签 mysql sql json

给定表 t 中的 JSON 对象类型列,例如

| id | obj                                | 
| -- | ---------------------------------- |
| 1  | { "params": { "id": [13, 23]} }    |
| 2  | { "params": { "id": [13, 24]} }    |
| 3  | { "params": { "id": [11, 23, 45]} }|

和一个数值列表,例如[12、23、45]

我们需要检查每条记录是否包含给定列表中的值。 所以,期望的结果是

| id | matches  |
| -- | -------- |
| 1  | [23]     |
| 3  | [23, 45] |

有人可以帮忙查询 MySQL 8 吗? 谢谢!

最佳答案

你可以使用json_table:

select t2.id, t2.n_obj from (
   select t1.id, (select json_arrayagg(ids.v) 
       from json_table(t1.obj, "$.params.id[*]" columns(v text path '$')) ids 
       where json_contains('[12, 23, 45]', ids.v, '$')) 
   n_obj from t t1) t2 
where t2.n_obj is not null;

关于mysql - 在 MySQL 的 JSON 数组字段中查找匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70957415/

相关文章:

php - 使用 angularjs php mysql 进行实时通知

sql - 宇宙数据库 : Query documents by time interval using partition key

Java:Jackson 数据绑定(bind)无法从 JSON 文件映射整个类

json - 将文件作为字符串传递给 Github Gist REST API

mysql - 如何从 Laravel 中的关系中获取 Sum

MySQL LEFT JOIN json 字段与表中的另一个 id

MySQL:正则表达式和通配符

mysql - 从 sql server 表创建 mysql View

mysql - SQL连接同一个表

java - 如何在 Java 中解析 JSON