我正在使用以下带有3个左联接的查询:
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
这需要一些时间(2-3秒),这并不理想。
每个查询花费的时间不到100毫秒,但是在一起(大概是由于连接的原因)要花很多时间才能完成。
有人知道有其他方法可以使用不同的联接方法来优化此操作吗?或者这是唯一的选择吗?
答案 0 :(得分:1)
在您已经使用联接的情况下,我认为在这种情况下您不需要子查询。如果我认为您的表结构和数据正确,则无需分组。尚未尝试过,但是以下内容应能提供与原始查询相同的结果,但速度要快得多(且可读):
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