如何优化这个复杂的SQL查询?

时间:2018-03-09 00:46:35

标签: sql ms-access subquery

我在msaccess数据库查询中运行了以下SQL查询,在好的计算机中需要几秒钟,4秒或5秒。但在客户端机器需要更多...我必须优化此查询。 我尝试在表Lins和MKT等表格中制作索引。而且似乎变得更好了, 问题是我有8个像这样的查询一个接一个地运行..而且它的开启速度非常慢,超过400.000条记录

SELECT LINs.LIN,
       Sum(VentasDet.Cantidad) AS SumaDeCantidad
FROM ((
         (SELECT *
          FROM ventas
          WHERE (CBTE='COT'
                 OR CBTE='FCA'
                 OR CBTE='FCB'
                 OR CBTE='PR'
                 OR CBTE='RTO'
                 OR CBTE='TK')
            AND (Suc=0
                 OR Suc=1
                 OR Suc=2
                 OR Suc=4
                 OR Suc=5)
            AND (Caja=0
                 OR Caja=1
                 OR Caja=2)
            AND (PRDO='12-2017'
                 OR PRDO='11-2017'
                 OR PRDO='10-2017'
                 OR PRDO='09-2017')
            AND (MKT=1
                 OR MKT=2
                 OR MKT=3
                 OR MKT=4
                 OR MKT=5) ) AS Ventas
       INNER JOIN
         (SELECT *
          FROM VentasDet
          WHERE LIN<>'0-'
            AND LIN<>'1AS'
            AND LIN<>'1VF'
            AND LIN<>'NEW'
            AND LIN<>'OSE'
            AND LIN<>'OLJ'
            AND LIN<>'OS-O' ) AS VentasDet ON (Ventas.Numero = VentasDet.Numero)
       AND (Ventas.Suc = VentasDet.Suc)
       AND (Ventas.CBTE = VentasDet.CBTE))
      INNER JOIN
        (SELECT Codigo,
                MaMi
         FROM Clis
         WHERE MaMi=0
           OR MaMi=1
           OR MaMi=2 ) AS Clis ON Ventas.Cli = Clis.Codigo)
INNER JOIN LINs ON VentasDet.LIN = LINs.Codigo
GROUP BY VentasDet.LIN,
         LINs.LIN
ORDER BY Sum(VentasDet.Cantidad) DESC

1 个答案:

答案 0 :(得分:0)

你可以尝试下面看它是否有任何区别? 1.制作一张中间牌加入CBTE; 2.制作一张中间表VentasDet;

create table CBTE (CBTE varchar(3));
insert into CBTE values('COT', 'FCA', 'FCB', 'PR','RTO', 'TK');


create table LIN (LIN varchar(4));
insert into LIN values('0-','1AS','1VF','NEW','OSE','OLJ','OS-O');


( SELECT *
          FROM VentasDet V
         left join LIN L on v.Lin=L.Lin where L.Lin is null) AS VentasDet