[Solved] Howto rewrite MySQL NOT IN query using a join?
Looking to automatically optimize YOUR SQL query? Start for free.

EverSQL Database Performance Knowledge Base

Howto rewrite MySQL NOT IN query using a join?

Database type:

i use a sql query like this to get some results i need:

SELECT
    *
FROM
    pictures p
WHERE
    p.id NOT IN 
        (
            SELECT
                picture_id
            FROM
                guesses g
            WHERE 
                g.user_id = XXX 
        )
    AND
        p.user_id != XXX
;

Relation is as follows: A user has many pictures and a picture belongs to one user. A user has many guesses and a guess belongs to one picture. The tricky part is that a user is only allowed one guess for the same picture.

XXX = $user_id

I guess that there is a way to rewrite this sub-select using a left join but i can't get it working.

Can anyone help?

Anja

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. Avoid Selecting Unnecessary Columns (query line: 2): Avoid selecting all columns with the '*' wildcard, unless you intend to use them all. Selecting redundant columns may result in unnecessary performance degradation.
  2. 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.
  3. 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 `guesses` ADD INDEX `guesses_idx_user_id_xxx_picture_id` (`user_id`,`XXX`,`picture_id`);
ALTER TABLE `pictures` ADD INDEX `pictures_idx_user_id` (`user_id`);
The optimized query:
SELECT
        * 
    FROM
        pictures p 
    WHERE
        NOT EXISTS (
            SELECT
                1 
            FROM
                guesses g 
            WHERE
                (
                    g.user_id = g.XXX
                ) 
                AND (
                    p.id = g.picture_id
                )
        ) 
        AND p.user_id != p.XXX

Related Articles



* original question posted on StackOverflow here.