Nested query inside Logical operator OR not working in meta_query

I’ve been trying this for hours now and I have searched and haven’t gotten a clue. I am trying to make a nested query with OR operator as a parent and AND operator inside it as child. The page keeps on loading and results are not shown. While on the other hand, if I make AND as parent then it works. Here is my code:

$compare_array = array(
    'relation' => 'OR',
    array(
        'relation' => 'AND',
        array(
            'key'       => 'property_size',
            'value'     => '15',
            'type'      => 'numeric',
            'compare'   => '='
        ),
        array(
            'key'       => 'property-type',
            'value'     => 'marla',
            'type'      => 'CHAR',
            'compare'   => 'LIKE'
        )
    ),
    array(
        'relation' => 'AND',
        array(
            'key'       => 'property_size',
            'value'     => '15',
            'type'      => 'numeric',
            'compare'   => '='
        ),
        array(
            'key'       => 'property-type',
            'value'     => 'Kanal',
            'type'      => 'CHAR',
            'compare'   => 'LIKE'
        )
    )

);

$meta_query[] = $compare_array;

1 Answer
1

I can see from above query that you are willing to do following thing.

Get all post if property_size is 15 AND property-type is marla OR Kanal.

The SQL will be like %marla% OR like %Kanal% this is equivalent to like %marla Kanal% this will not make much difference (I assume)

So you can minimize this query in this way

$compare_array = array(
    'relation' => 'AND',
    array(
        'key'       => 'property_size',
        'value'     => '15',
        'type'      => 'numeric',
        'compare'   => '='
    ),
    array(
        'key'       => 'property-type',
        'value'     => 'marla Kanal',
        'type'      => 'CHAR',
        'compare'   => 'LIKE'
    )
);

In my testing it reduce the query time by 428 ms

SQL like is expensive so if you are matching exact value then use IN with array of values.

array(
        'key'       => 'property-type',
        'value'     =>  array('marla', 'Kanal'),
        'type'      => 'CHAR',
        'compare'   => 'IN'
    )

Leave a Comment