HiveBrain v1.2.0
Get Started
← Back to all entries
patternsqlMinor

Select from a list of values from JSON encoded data

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
jsonencodedlistvaluesselectfromdata

Problem

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.

Solution

I got a solution:

-
Single check of value in JSON array

SELECT * FROM `nw_object_detail` 
WHERE ((`details` like '%"screen_type":"%LED%"%'))


-
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 .= ')';

Code Snippets

SELECT * FROM `nw_object_detail` 
WHERE ((`details` like '%"screen_type":"%LED%"%'))
SELECT * FROM `nw_object_detail`
WHERE ((`details` like '%"screen_type":[%"%LCD%"%]%')
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 .= ')';

Context

StackExchange Database Administrators Q#68038, answer score: 3

Revisions (0)

No revisions yet.