[英]Search json data in mysql
I have json data stored in a MySQL database like this:我将 json 数据存储在 MySQL 数据库中,如下所示:
{"size":["S","M","L"],"in_stock":["1","1","1"],"articleid":["102802","102803","102804"]}
I'm trying to get only data in return that has size:M with the following SELECT:我正在尝试仅获取具有size:M 的数据作为回报,并使用以下 SELECT:
SELECT * FROM products WHERE id>0 AND sizescolors REGEXP '"size":"([^"])"M"([^"])"'
The only problem is, it return zero results.唯一的问题是,它返回零结果。 Is there something wrong with my regular expression?我的正则表达式有问题吗?
Thank you in advance, Dennis提前谢谢你,丹尼斯
Something like this with php:像这样的 php:
$Json = json_decode($Data['rowName']);
foreach($Json->size as $Size){
$Sizes[$Size] = $Size;
foreach($Json->in_stock as $InStock){
$Stock[] = $InStock;
}
}
if($Stock['0']==TRUE){
echo $Sizes['S'] . " Is in stock (".$Stock['0']." left)<br/>";
}
else{
echo $Sizes['S'] . " not in stock.<br/>";
}
if($Stock['1']==TRUE){
echo $Sizes['M'] . " Is in stock (".$Stock['1']." left)<br/>";
}
else{
echo $Sizes['M'] . " not in stock.<br/>";
}
if($Stock['2']==TRUE){
echo $Sizes['L'] . " Is in stock (".$Stock['2']." left)";
}
else{
echo $Sizes['M'] . " not in stock.";
}
<?php
//fetch the json data from mysql and store in variable
$str ='{"size":["S","M","L"],"in_stock":["1","1","1"],"articleid":["102802","102803","102804"]}';
//decode json into associate array
$data=json_decode($str,true);
//variable to get position of size=M
//position is needed because may size=M may be at any location like size=M, L, S, XL, XLL, etc
$i=0;
foreach($data as $key=>$value)
{
if($data['size'][$i]=='M')//if size M got. then at that same location find data
{
$size=$data['size'][$i];
$in_stock=$data['in_stock'][$i];
$articleid=$data['articleid'][$i];
echo $size." ".$in_stock." ".$articleid;
break;//to stop further search
}
$i++;
}
?>
Mysql 5.7 support the JSON data types and a few functions related. Mysql 5.7 支持 JSON 数据类型和一些相关的功能。
https://dev.mysql.com/doc/refman/5.7/en/json-functions.html https://dev.mysql.com/doc/refman/5.7/en/json-functions.html
SELECT * FROM products
WHERE JSON_UNQUOTE( JSON_EXTRACT(sizescolors, '$.size')) = 'M'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.