如何优化此SQL查询

时间:2013-10-14 09:45:41

标签: mysql sql

此查询需要3秒钟,我想让它运行得更快。 请提供任何建议

SELECT Concat(e.estimate1, '-', e.estimate2) AS estimateid,
       e.estimatetype,
       e.createdby,
       e.estimateid AS estID,
       e.`layoutnumber`,
       sd.specno,
       sd.samplenumber,
       sd.numberon,
       c.customerid,
       c.custprosname,
       c.`custtype`,
       (SELECT Count(*)
        FROM  (SELECT e.estimate1
               FROM   `simpleestimatedetails` sd,
                      estimatemaster e,
                      `vcustomer_prospect` c
               WHERE  c.customerid IN ( e.customernumber, e.prospectnumber )
                      AND ( e.estimate1 LIKE '%1%' )
                      AND ( sd.`simpleestid` = e.estimateid )) AS counter) AS
       counter
FROM   `simpleestimatedetails` sd,
       estimatemaster e,
       `vcustomer_prospect` c
WHERE  c.customerid IN ( e.customernumber, e.prospectnumber )
       AND ( e.estimate1 LIKE '%1%' )
       AND ( sd.`simpleestid` = e.estimateid );

2 个答案:

答案 0 :(得分:1)

在您的SQL查询中,'Counter'正在调用多个表的冗余连接。

请忽略计数器列,并尝试将值作为最后一次从SQl查询返回的总行数。

希望这会增强查询性能。您将通过以下查询获得所需的结果

select concat(e.estimate1,'-',e.estimate2) as estimateid,
         e.estimatetype,
         e.CreatedBy,
         e.EstimateID as estID,
         e.`LayoutNumber`,
          sd.specNo,
          sd.SampleNumber,
          sd.NumberON, c.customerid,
          c.CustProsName,
          c.`CustType`
             from `simpleestimatedetails` sd,
              estimatemaster e,
              `vcustomer_prospect` c
             where c.customerid in (e.customernumber,e.ProspectNumber)
             and (e.estimate1 like '%1%')
              and (sd.`SimpleEstID`=e.estimateid);

注意:总行数将为您提供计数器

的值

答案 1 :(得分:1)

SELECT Concat(e.estimate1, '-', e.estimate2) AS estimateid,
       e.estimatetype,
       e.createdby,
       e.estimateid AS estID,
       e.`layoutnumber`,
       sd.specno,
       sd.samplenumber,
       sd.numberon,
       c.customerid,
       c.custprosname,
       c.`custtype`
  FROM estimatemaster e Inner Join
       `vcustomer_prospect` c
    On c.customerid IN ( e.customernumber, e.prospectnumber )
 Inner Join `simpleestimatedetails` sd
    On sd.`simpleestid` = e.estimateid
 WHERE e.estimate1 LIKE '%1%'

注意:我删除了计数器列。如果您是从某个前端进行的,那么您可以通过查看查询组件的RowsAffectedRowCountRecordsCount或Somthing Similar属性来获取计数器值。