Mysql – Multiple left join hangs server

join;MySQLperformancequery-performance

I have a problem with left join query. It connects 3 tables and calculates sales value for categories.

Query:

SELECT
    categories.name,
    categories.id,
    SUM((orders_products.product_price_gross + orders_products.option_price)*(1 - (orders_products.rebate/100))  * orders_products.product_qty) AS suma
FROM product_categories
LEFT JOIN orders_products 
    ON product_categories.product_id = orders_products.product_id
LEFT JOIN categories
    ON product_categories.category_id = categories.id
GROUP BY categories.name, categories.id
ORDER BY suma DESC


    categories
id  int(11) NO  PRI     NULL    auto_increment
parent_categories   int(11) NO      0   
name    varchar(250)    NO      

orders_products
id  int(11) NO  PRI     NULL    auto_increment
order_id    int(11) NO  PRI     0   
product_id  int(11) NO      0   
product_name    varchar(255)    NO          
product_price_gross     double(8,2) NO      0.00    
product_qty     int(3)  NO      0           
option_price    decimal(8,2)    NO      NULL    
discount    decimal(8,2)    NO      NULL    
rebate  int(11) NO      NULL    

product_categories
product_id  int(11) NO  MUL     0   
category_id     int(11) NO      0   
ord     int(11) NO      0   
id  int(11) NO  PRI     NULL    auto_increment

Tables are big – categories – 2808 rows, product_categories – 84 000, orders_products – 47500

It should display list of categories and sales values for each one. Instead of that it hangs the server totally and restart is needed. I used many different queries from StackOverflow but any of them hangs server. I have no idea why.

Best Answer

I am not so familiar with mysql. BUT. You should always connect relations on primary - foreign key. You join PRODUCT_CATEGORIES with ORDERS_PRODUCT on product_id which are foreign key and I am not sure if they can be NULL. Run EXPLAIN select and you will know what your query planner is doing.

Related Question