我在执行多个连接的查询时遇到困难,并且对于大型记录集来说非常慢。这是查询:
SELECT
order_headers.*,
SUM(order_details.cost) AS amount,
CONCAT(organizations.card_first_name,
' ',
organizations.card_last_name) AS card_name
FROM
order_headers
INNER JOIN
organizations ON order_headers.organization_id = organizations.id
LEFT JOIN
order_details ON order_details.order_header_id = order_headers.id
LEFT JOIN
user_accounts ON user_accounts.organization_id = organizations.id
AND organizations.is_single_user = 1
WHERE
(status IN ('UNCHARGED' , 'ERROR'))
GROUP BY order_headers.id
HAVING SUM(order_details.cost) > 0
ORDER BY IF(organizations.is_single_user = 1,
(user_accounts.first_name + ' ' + user_accounts.last_name),
organizations.name) ASC
LIMIT 100 OFFSET 0
我可以从查询中删除一些内容(尽管我的应用程序需要运行),这可以将查询速度提高到~0.183秒。其中包括:
非常感谢任何帮助。
答案 0 :(得分:0)
首先,您有一个似乎没必要的条件ORDER BY
子句。 JOIN
user_accounts
organizations
仅指定is_single_user = 1
ORDER BY
。但是你正在使用它作为is_single_user = 1
条件的一部分。在这种情况下,ORDER BY
永远都是真的。
请尝试修改后的SELECT
order_headers.*,
SUM(order_details.cost) AS amount,
CONCAT(organizations.card_first_name,
' ',
organizations.card_last_name) AS card_name
FROM
order_headers
INNER JOIN
organizations ON order_headers.organization_id = organizations.id
LEFT JOIN
order_details ON order_details.order_header_id = order_headers.id
LEFT JOIN
user_accounts ON user_accounts.organization_id = organizations.id
AND organizations.is_single_user = 1
WHERE
(status IN ('UNCHARGED' , 'ERROR'))
GROUP BY order_headers.id
HAVING SUM(order_details.cost) > 0
ORDER BY user_accounts.first_name, user_accounts.last_name
LIMIT 100 OFFSET 0
子句:
user_accounts.first_name + user_accounts.last_name
其次,确保在所有外键(您正在加入的外键)上设置索引,并且可能在{{1}}上设置索引以帮助进行排序。