日期:2014-05-18  浏览次数:20462 次

数据库里有100多万条数据
现在数据库里有1000多万条数据,我使用了view,用union语句将有关联的表连接起来,这个一个view数据有1000多万条数据

code条码,color颜色,44,55,66,77,88为数量


上面的执行很快

我先用

select   a.code,a.color   44=sum(select   sum(44)   from   view   as   b   where   b.code=a.code   and   b.color=a.color)

from   view   as   a   group   by   a.code,a.color

后面的55,66,77,88和44语句一样

这样的结果出来是非常的慢,请问大家有什么方法可以解决呢



------解决方案--------------------
select sum(44) from view as b where b.code=a.code and b.color=a.color

把 这个也建成视图 试下。

视图建立索引查起来快点。可惜用了Union好像不能建立索引。。
------解决方案--------------------
可能最好的办法就是利用周末,先计算出所有的结果
然后把这张表作为统计信息表,今后每次业务修改或者增加、删除view的数据,同时更新统计信息表,化整为零法。
对经常需要的查询可以这么设计。
或许你的应用做不到,但我觉得这么做是一劳永逸的事情
------解决方案--------------------
select a.code,a.color,
[44]=sum(case 数量 when 44 then 1 else 0 end),
[55]=sum(case 数量 when 55 then 1 else 0 end),
[66]=sum(case 数量 when 66 then 1 else 0 end),
[77]=sum(case 数量 when 77 then 1 else 0 end),
[88]=sum(case 数量 when 88 then 1 else 0 end)
from [view] as a group by a.code,a.color
------解决方案--------------------
其实用触发器比较容易实现吧