简体   繁体   中英

Speed up Mysql query with 3 left joins

I'm using the following query with 3 left joins:

SELECT `Date`,`Year`,`Month`, `Day`,`Hour`, `Order Line Total` from 

(SELECT order_updated_at, DATE(order_updated_at) as `Date`,  YEAR(order_updated_at) as `Year`, MONTHNAME(order_updated_at) as `Month`, DAYNAME(order_updated_at) as `Day`, order_time_hour_num as `Hour`, orderline_product_id, order_staff_member_id, (orderline_product_total * orderline_product_quantity) AS `Order Line Total` FROM order-lines-table) ORDERS

LEFT JOIN
(SELECT staff_id, first_name, last_name, concat(first_name, ' ', last_name) AS `Staff Member`
FROM staff-table) STAFF
ON ORDERS.order_staff_member_id = STAFF.staff_id

LEFT JOIN
(SELECT * from  
(SELECT category_id, product_id, product_name
FROM products-table group by product_id) PRODUCTS

LEFT JOIN     
(SELECT categories_id, categories_name
FROM categories-table group by categories_id) CATEGORIES
ON PRODUCTS.category_id = CATEGORIES.categories_id) PRODUCTS_AND_CATGORIES

ON ORDERS.orderline_product_id = PRODUCTS_AND_CATGORIES.product_id

This is taking a little while to run (2-3 seconds) which is not ideal.

Individually each query takes less than 100ms but together (presumably due to the joins) it takes many times the sum of the parts to complete.

Does anyone know any way to optimise this using a different method of joins or is this the only option?

I think you don't need subqueries in this case when you're already using joins. You do not need grouping neither if I interpret you're table structure and data right. Haven't tried it, but the following should give the same result as the original query but considerably faster (and readable):

SELECT 
    DATE(order_updated_at) as `Date`,
    YEAR(order_updated_at) as `Year`,
    MONTHNAME(order_updated_at) as `Month`,
    DAYNAME(order_updated_at) as `Day`,
    order_time_hour_num as `Hour`, 
    (orderline_product_total * orderline_product_quantity) AS `Order Line Total`
FROM order-lines-table olt
LEFT JOIN staff-table st ON olt.order_staff_member_id = st.staff_id
LEFT JOIN products-table pt ON olt.orderline_product_id = pt.product_id
LEFT JOIN categories-table ct ON pt.categories_id = ct.categories_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM