php - 针对嵌套 JSON 字段、MYSQL、PHP 的 QUERY
问题描述
我有这样的结构:
{"placards":
[
{"barcode": "string", "destination":"string", "weight":"string"},
{etc...}
]
}
存储在 MYSQL 数据库中的单个列上。
我正在尝试搜索特定的条形码,并返回该条形码在该行中该 json 结构内的整行。
我尝试了两种方法,都在堆栈溢出时发现,但我没有在一种方法中得到结果,下面我将发布后者的错误。
attempt1:
"SELECT * FROM table WHERE placards[*->barcode] = ".$job->events[0]->imcb;
attempt2:
$sampleBC = $job->events[0]->imcb;
$sql = 'SELECT * FROM(
SELECT data_column->"[*]" as row
from table
where $sampleBC IN JSON_EXTRACT(data_column, ""
)
WHERE row->".barcode" = $sampleBC';
这些方法都没有在 $stmt->error 上给出错误,但我实际上无法通过此查询成功获取任何内容。
解决方案
您可以使用json_contains()
:
select *
from mytable
where json_contains(data_column, '{ "barcode": "foo" }' , '$.placards')
'placards'
此短语为:在包含候选对象的键/值对的路径下的数组中搜索任何元素'{ "barcode": "foo" }'
,其中'foo'
是您搜索的条形码值。
set @data_column =
'{
"placards": [
{"barcode": "foo", "destination":"string", "weight":"string"},
{"barcode": "bar", "destination":"string", "weight":"string"}
]
}';
select json_contains(@data_column, '{ "barcode": "foo" }' , '$.placards') is_a_match;
| is_a_match |
| ---------: |
| 1 |
select json_contains(@data_column, '{ "barcode": "baz" }' , '$.placards') is_a_match;
| is_a_match |
| ---------: |
| 0 |
从 MySQL 8.0.17 开始,你甚至可以在嵌套的 json 数组上创建多值索引,因此数据库不需要对这个查询执行全表扫描:
alter table mytable
add index myidx( (cast(data_column -> '$.placards' as unsigned array)) );
推荐阅读
- javascript - 有没有办法从 html 文档中的数据库中删除对象?(django)
- python - 为什么输入“完成”时会出错?
- jenkins - 如何将环境变量传递给 Jenkins Pipeline Tools 部分
- r - 如何在 R 中使用过滤选项?
- c - C 数据类型大小 intmax_t 与任何其他整数、void * 与任何其他指针
- algorithm - 这有重叠的子问题吗?
- amazon-dynamodb - DynamoDB 事务
- php - 搜索数据时如何将我的自定义 URL 获取到 URL 浏览器
- sql - 我的订单表中的地址列如何引用多种类型的地址格式?
- jquery-ui - 如何在jquery ui中的父元素的每个子元素上单独删除一个元素?