简体   繁体   中英

Search json data in mysql

I have json data stored in a MySQL database like this:

{"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:

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:

$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.

https://dev.mysql.com/doc/refman/5.7/en/json-functions.html

SELECT * FROM products 
WHERE JSON_UNQUOTE( JSON_EXTRACT(sizescolors, '$.size')) = 'M'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM