mysql查询运行缓慢
Posted
技术标签:
【中文标题】mysql查询运行缓慢【英文标题】:mysql query run slow 【发布时间】:2015-09-30 09:14:13 【问题描述】:我有这个问题
SELECT debtDinar,
creditDinar,
debtDollar,
creditDollar AS creditDollar,
companyID,
costCenter,
accountnumber,
accountName,
activityNo,
activityName,
name,
if((debtDinar-creditDinar) >= 0.000,(debtDinar-creditDinar),0.000) AS debtDinarEx,
if((debtDinar-creditDinar) >= 0.000,0.000,abs(debtDinar-creditDinar)) AS creditDinarEx,
if((debtDollar-creditDollar) >= 0.00,(debtDollar-creditDollar),0.00) AS debtDollarEx,
if((debtDollar-creditDollar) >= 0.00,0.00,abs(debtDollar-creditDollar)) AS creditDollarEx
FROM
(SELECT SUM(recordsdetails.debtor) AS debtDinar,
SUM(recordsdetails.creditor) AS creditDinar,
SUM(recordsdetails.debtDollar) AS debtorDollar,
SUM(recordsdetails.creditDollar) AS creditDollar,
companies.name AS name,
recordsdetails.companyID AS companyID,
costCenter AS costCenter,
accounts.accountnumber AS accountnumber,
accounts.accountName AS accountName,
recordsdetails.activityNo AS activityNo,
recordsdetails.activityName AS activityName
FROM (records,
accounts
JOIN (companies
LEFT JOIN recordsdetails on((recordsdetails.companyID = companies.companyID))))
WHERE left(recordsdetails.accountnumber,1)=accounts.accountnumber
AND (recordsdetails.companyID = 1)
GROUP BY accounts.accountnumber,
costCenter
ORDER BY accounts.sortorder) AS recordsdetails
获取数据的速度非常慢,大约需要 30-60 秒,当数据增加时它会变得更慢,有什么想法可以让这个查询变得简单
【问题讨论】:
显示一些虚拟数据......你想要达到的目标 索引索引索引 看起来不对:WHERE left(recordsdetails.accountnumber,1)=accounts.accountnumber
不,它工作正常,但我认为它太慢了,因为我正在使用select from select
【参考方案1】:
我先整理一下您的查询。您使用了混合连接语法,缺少别名并将临时表重命名为与真实表相同的名称,因此很难跟踪正在发生的事情。
你真的在使用表records
吗?它似乎是在没有任何条件的情况下交叉加入的..
您也可以重构 SELECT FROM (SELECT ... )
。
一旦这一切都干净整洁,您应该运行EXPLAIN ...
并查看正在使用哪些索引以及查询可能在哪里失败。
【讨论】:
这是我的全部标准,from (records,accounts join (companies left join recordsdetails on((recordsdetails.companyID = companies.companyID)))) WHERE left(recordsdetails.accountnumber,?)=accounts.accountnumber AND (recordsdetails.companyID =?) AND (recordsdetails.recordDate BETWEEN ? AND ?) AND (recordsdetails.accountNumber LIKE ? ) group by accounts.accountnumber,costCenter order by accounts.sortorder) AS recordsdetails
@AlaaEssam 我可以看到,但是您使用的是来自records
的哪些列? costCenter
在那个表里吗?以上是关于mysql查询运行缓慢的主要内容,如果未能解决你的问题,请参考以下文章