We help IT Professionals succeed at work.
Get Started

MySQL Join Problem - WHERE NOT IN

Last Modified: 2012-05-06
Using MySql 5.1.30.

I have an order_history table and a order_history_products table.  The products table has many rows for each order in the orders table.

I need to know what orders do not contain certain products, for example:

SELECT * FROM `order_history` WHERE order_id NOT IN (SELECT  order_history.order_id
      FROM order_history INNER JOIN order_history_products ON order_history.order_id = order_history_products.order_id
      WHERE order_history_products.product_name = 'Pencils'
      GROUP BY order_history.order_id)

In theory this query would work, but the query takes 10+ minutes to execute.

If I execute the query separately it takes only seconds to finish (the inner join).

Example of tables:

row 1
    order_id: 5000
    order_fullname: John Doe

row 1
    product_name: Pencils
row 2
    product_name: Paper
row 3
    product_name: Paperclips


Also, in the orders_history table, there are multiple rows for the same customer, so I'll be grouping the end result by order_fullname.  Just FYI.

I'm open to any suggestions, even reconstructing the structure if necessary.

Thank you.

Watch Question
This problem has been solved!
Unlock 1 Answer and 23 Comments.
See Answer
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE