[Solved] Need Optimized Query which take data from three tables

EverSQL Database Performance Knowledge Base

Need Optimized Query which take data from three tables

Three tables

accounts, products, users
  1. Select users id and email from users table where there id are in accounts
  2. Then filter them out from products table where user bought more than 3 products (Need to count users in product table and exclude a user if his count is more than 3).

       SELECT id, email
    FROM  users 
    WHERE id
    IN (
    SELECT user_id
    FROM accounts
    WHERE users.id = user_id
    )
    

I got all users id and emails, but now I need to filter them out from product table. In product table I have 'product_id' and 'leader_id', which is user id.

I need optimized query, because tables are very big

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. Replace In Subquery With Correlated Exists (modified query below): In many cases, an EXISTS subquery with a correlated condition will perform better than a non correlated IN subquery.
Optimal indexes for this query:
ALTER TABLE `accounts` ADD INDEX `accounts_idx_user_id` (`user_id`);
The optimized query:
SELECT
        users.id,
        users.email 
    FROM
        users 
    WHERE
        EXISTS (
            SELECT
                1 
            FROM
                accounts 
            WHERE
                (
                    users.id = accounts.user_id
                ) 
                AND (
                    users.id = accounts.user_id
                )
        )

Related Articles



* original question posted on StackOverflow here.