根据 JSON-对象键值在 table 中查找行
Find row in table depending on JSON-Object key-value
我有一个 MySQL 数据库,其中有一个 table 用户。这个 table 有一些列。在名为 actions 的列中,存储了 JSON 个对象。例如:
{
"name": "joe",
"tasks": [
{
"id": "1",
"type": "wait",
"value": "s*2*c"
},
{
"id": "2",
"type": "run",
"value": "a*c*47I*x"
}
]
}
我的目标是检索所有包含 JSON 对象且类型为“运行”且值包含多个星号 * 的行。考虑到数组任务可以有多个不同顺序的对象,这可能吗?
您需要为此使用 JSON_TABLE():
mysql> select j.* from users cross join
-> json_table(users.actions, '$.tasks[*]' columns ( type varchar(10) path '$.type', value varchar(20) path '$.value')) as j
-> where type='run' and value like '%*%*%';
+------+-----------+
| type | value |
+------+-----------+
| run | a*c*47I*x |
+------+-----------+
如果您仍在使用MySQL 5.x,那么如果您需要以这种方式进行搜索,最好的选择是将数据存储在正常的行和列中。也就是说,不要将数据存储为 JSON.
事实上,即使您有 MySQL 8.0,这也是最佳选择。下面的不是更简单吗?
select user_id from tasks
where type='run' and value like '%*%*%';
我有一个 MySQL 数据库,其中有一个 table 用户。这个 table 有一些列。在名为 actions 的列中,存储了 JSON 个对象。例如:
{
"name": "joe",
"tasks": [
{
"id": "1",
"type": "wait",
"value": "s*2*c"
},
{
"id": "2",
"type": "run",
"value": "a*c*47I*x"
}
]
}
我的目标是检索所有包含 JSON 对象且类型为“运行”且值包含多个星号 * 的行。考虑到数组任务可以有多个不同顺序的对象,这可能吗?
您需要为此使用 JSON_TABLE():
mysql> select j.* from users cross join
-> json_table(users.actions, '$.tasks[*]' columns ( type varchar(10) path '$.type', value varchar(20) path '$.value')) as j
-> where type='run' and value like '%*%*%';
+------+-----------+
| type | value |
+------+-----------+
| run | a*c*47I*x |
+------+-----------+
如果您仍在使用MySQL 5.x,那么如果您需要以这种方式进行搜索,最好的选择是将数据存储在正常的行和列中。也就是说,不要将数据存储为 JSON.
事实上,即使您有 MySQL 8.0,这也是最佳选择。下面的不是更简单吗?
select user_id from tasks
where type='run' and value like '%*%*%';