Slow distinct query in SQL Server over large dataset

前端 未结 10 2629
情深已故
情深已故 2021-02-14 00:27

We\'re using SQL Server 2005 to track a fair amount of constantly incoming data (5-15 updates per second). We noticed after it has been in production for a couple months that on

10条回答
  •  南旧
    南旧 (楼主)
    2021-02-14 00:50

    An indexed view can make this faster.

    create view alltypes
    with schemabinding as
    select typename, count_big(*) as kount
    from dbo.types
    group by typename
    
    create unique clustered index idx
    on alltypes (typename)
    

    The work to keep the view up to date on each change to the base table should be moderate (depending on your application, of course -- my point is that it doesn't have to scan the whole table each time or do anything insanely expensive like that.)

    Alternatively you could make a small table holding all values:

    select distinct typename
    into alltypes
    from types
    
    alter table alltypes
    add primary key (typename)
    
    alter table types add foreign key (typename) references alltypes
    

    The foreign key will make sure that all values used appear in the parent alltypes table. The trouble is in ensuring that alltypes does not contain values not used in the child types table.

提交回复
热议问题