MySQL Performance – Select from JSON Encoded Data

MySQLperformancequery-performance

I have saved the details of the product in JSON format.
I am wondering how to select from a list of values from a "JSON_ENCODED DATA"

For Example
I want to select TV with screen_type as LED or LCD.

And the value is saved as

{"screen_size":"22 - 24", "screen_type":"LED", "smart_tv":"no", "3d":"no", "resolution":"HD Ready", "hdmi":"1", "usb":"1"}

It is possible to do with UNION query like:

SELECT * FROM `nw_object_detail` WHERE `details` LIKE '%"screen_type":"LED"%'  
UNION  
SELECT * FROM `nw_object_detail` WHERE `details` LIKE '%"screen_type":"LCD"%'

But the query will be too lengthy if there are lot of choices.
Is there are any solution in a simpler way.

Best Answer

I got a solution:

  1. Single check of value in JSON array

    SELECT * FROM `nw_object_detail` 
    WHERE ((`details` like '%"screen_type":"%LED%"%'))
    
  2. One value from multiple possibilities

    SELECT * FROM `nw_object_detail`
    WHERE ((`details` like '%"screen_type":[%"%LCD%"%]%') 
    

PHP Solution

if(count($options)>1): 
    $condition = '(';
    $count = 1;
    foreach( $options as $option ): 
        $condition .= '(`details` like \'%"'.$key.'":[%"%'.$option.'%"%]%\')';
        if(count($options)!=$count): 
            $condition .= ' OR ';
        endif;
    endforeach;
$condition .= ')';