查询非常慢

时间:2012-12-06 08:57:35

标签: sql-server sql-server-2008

我有桌子

表1

epid        etid        id          EValue       reqdate
----------- ----------- ----------- ------------ ----------
15          1           1           498925307069 2012-01-01
185         1           2           A5973FC43CE3 2012-04-04
186         1           2           44C6A4B776A2 2012-04-05
205         1           2           7A0ED3F1DA13 2012-09-19
206         1           2           77771D65F9C4 2012-09-19
207         1           2           AD74A4AA41BD 2012-09-19
208         1           2           9595ABE5A0C8 2012-09-19
209         1           2           7611D2FB395B 2012-09-19
210         1           2           04A510D6067A 2012-09-19
211         1           2           24D43EC268F8 2012-09-19

表2

PEId        Id          EPId
----------- ----------- -----------
43          9           15
44          10          15
45          11          15
46          12          15
47          13          15
48          14          15
49          15          15
50          16          15
51          17          15
52          18          15

表3

PLId        PEId        Id          ToPayId
----------- ----------- ----------- -----------
71          43          9           1
72          43          9           2
73          44          10          1
74          44          10          2
75          45          11          1
76          45          11          2
77          46          12          1
78          46          12          2
79          47          13          1
80          47          13          2

我希望在表3中获得一个小于8的id,并在表2中按peid排序,

我写了查询

SELECT Top 1  ToPayId FROM 
(
    SELECT Count(pl.ToPayId) C, pl.ToPayId 
    FROM table3 pl 
    INNER JOIN table2 pe ON pl.peid = pe.peid 
    INNER JOIN table1 e ON pe.epid = e.epid
    WHERE e.EtId=1 GROUP BY pl.ToPayId 
) As T 
INNER JOIN table2 p ON T.ToPayId= p.Id 
WHERE C < 8 ORDER BY p.PEId ASC

此查询在存储过程中执行的次数超过1000次,具体取决于使用while条件时user-defined-table-type中的条目。

但由于我们在每个表中都有数百万个条目,所以它非常慢。

有人可以建议更好的查询吗?

2 个答案:

答案 0 :(得分:0)

也许尝试使用having子句来摆脱选择

select table2.id as due
      from table3 inner join table2 on table2.PEId=table3.PEId...
      group by ...
      having count(due) <8
      order by ...

- &GT;表3中有一个冗余的Id列:看起来很无用,因为PEId和Id一对看起来很独特所以删除它并将表3的大小减少25%,从而提高db的性能

答案 1 :(得分:0)

将...因为您没有提供足够的样本数据,我不确定您的业务逻辑究竟是什么。这样我就可以盲目地修改代码。

SELECT ToPayId 
FROM (

    SELECT TOP 1 Count(pl.ToPayId) C, pl.ToPayId, pe.PEId
    FROM table3 as pl 
        INNER JOIN table2 as pe ON pl.peid = pe.peid AND pl.ToPayId = pe.Id
        INNER JOIN table1 e ON pe.epid = e.epid
    WHERE e.EtId=1
    GROUP BY pl.ToPayId, pe.PEId 
    HAVING Count(pl.ToPayId) < 8
    ORDER BY pe.PEId ASC    

) AS T