【问题标题】:How can I optimize this SQL query with JOINS and nested SELECT?如何使用 JOINS 和嵌套 SELECT 优化此 SQL 查询?
【发布时间】:2016-10-04 15:24:46
【问题描述】:

我的 SQL 查询需要大量时间来执行,因为事务表在某种程度上非常巨大。我正在寻找提高此查询性能的方法。

SELECT users.user_id, users.name as user, IFNULL(SUM(IF(transactions.recipient_account = users.account_id,transactions.money,0-transactions.money)),0) as total
FROM users as users
JOIN 
(SELECT account_id as system_account FROM accounts WHERE user_guid IS NULL AND name IS NULL LIMIT 1) as tmp
LEFT JOIN (transactions as transactions) 
   ON (users.account_id IN (transactions.sender_account,transactions.recipient_account))
WHERE (users.hidden = 0) 
   AND ((transactions.flags & 1) = 0 
   OR transactions.flags IS NULL)
GROUP BY users.user_guid 
ORDER BY total DESC 
LIMIT 0,5

我对索引很感兴趣,但我不确定如何在这里使用它们。

感谢您的任何帮助或建议。

【问题讨论】:

  • 请向我们提供解释结果,并向我们提供您在受影响表上的索引以及这些索引包含的字段。没有这些,任何答案都将基于纯粹的猜测。
  • 通常情况下,您将为查询的 where 子句中使用的列添加索引。您可以在这些列上添加/删除索引,看看它是否提高了性能。

标签: mysql sql query-performance


【解决方案1】:
accounts:  INDEX(user_guid, name, account_id)
users:  INDEX(hidden, account_id)

请为每张桌子提供SHOW CREATE TABLE;有了这个,我们可能会有进一步的建议。

Index Cookbook.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-10
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多