[Solved] complex and nested WHERE conditions in SQL with LEFT JOIN

EverSQL Database Performance Knowledge Base

complex and nested WHERE conditions in SQL with LEFT JOIN

I am trying to fetch posts with multiple filters, my database is as below,

"Meta" Table meta table

"Posts" Table post table

  SELECT p.id, p.title
        FROM posts p
        JOIN meta m ON p.id = m.object_id
        WHERE m.object_name='post'

        AND (m.meta_key, m.meta_value) IN (('location', 'new city'),('post_type', 'section'))
        GROUP BY p.id, p.title
        HAVING COUNT(DISTINCT m.id) = 2

I tried the above SQL and it works but trouble is if i nest more than two OR conditions with different numbers of filters i am getting wrong results.

just for explaining what i want , not sql :

            SELECT p.id, p.title
            FROM posts p
            JOIN meta m ON p.id = m.object_id
            WHERE m.object_name='post'
            AND
                                 (
                                    #SET 1 = (
                                       (m.meta_key = 'location' and m.meta_value = 'new city')
                                       or (m.meta_key = 'price' and m.meta_value = 100)
                                       or (m.meta_key = 'color' and m.meta_value = red)
                                    )

                                      OR

                                    #SET 2 = (
                                       m.meta_key = 'post_type' and m.meta_value = 'product'
                                       OR m.meta_key = 'location' and m.meta_value =  'delhi'
                                    )

                                 )
                          AND p.post_class='post'
              GROUP BY p.id, p.title
              HAVING if #SET 1 matched { COUNT(DISTINCT m.id) = 3 } elseIf #SET 2 matched { 
              COUNT(DISTINCT m.id) = 2 }

How to optimize this SQL query?

The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:

  1. Description of the steps you can take to speed up the query.
  2. The optimal indexes for this query, which you can copy and create in your database.
  3. An automatically re-written query you can copy and execute in your database.
The optimization process and recommendations:
  1. Create Optimal Indexes (modified query below): The recommended indexes are an integral part of this optimization effort and should be created before testing the execution duration of the optimized query.
  2. Explicitly ORDER BY After GROUP BY (modified query below): By default, the database sorts all 'GROUP BY col1, col2, ...' queries as if you specified 'ORDER BY col1, col2, ...' in the query as well. If a query includes a GROUP BY clause but you want to avoid the overhead of sorting the result, you can suppress sorting by specifying 'ORDER BY NULL'.
Optimal indexes for this query:
ALTER TABLE `meta` ADD INDEX `meta_idx_object_name` (`object_name`);
ALTER TABLE `posts` ADD INDEX `posts_idx_id_title` (`id`,`title`);
The optimized query:
SELECT
        p.id,
        p.title 
    FROM
        posts p 
    JOIN
        meta m 
            ON p.id = m.object_id 
    WHERE
        m.object_name = 'post' 
        AND (
            m.meta_key, m.meta_value
        ) IN (
            (
                'location', 'new city'
            ), (
                'post_type', 'section'
            )
        ) 
    GROUP BY
        p.id,
        p.title 
    HAVING
        COUNT(DISTINCT m.id) = 2 
    ORDER BY
        NULL

Related Articles



* original question posted on StackOverflow here.