设计SQL视图并提高性能

时间:2011-05-29 05:44:26

标签: tsql

我需要创建一个视图,业务场景如下所述

考虑我有桌面产品(所有产品信息)和设置(国家/州/城市的设置)

现在我必须创建一个视图,通过考虑设置来提供产品信息,有可能让城市/州/国家拥有自己的设置。 视图设计 这意味着首先我需要检查 1.任何城市都有自定义设置然后输出这些记录 UNION ALL 2.任何州都有自定义设置,然后通过在步骤1中排除此状态下的城市来输出这些记录 UNION ALL 3.任何国家/地区是否有自定义设置,然后通过在步骤1和步骤2中排除城市和州记录来输出这些记录

这是我想到的设计,设计有什么问题吗?

提高绩效 使用这种现有设计,在视图和基表上没有任何索引的情况下运行查询需要5分钟。

现在,提高性能的最佳选择是什么。 在基表上创建索引视图或创建索引?哪一个帮助我在几秒钟内运行查询:)

示例数据

产品表 enter image description here

设置表

enter image description here

预期产出

enter image description here

1 个答案:

答案 0 :(得分:1)

我无法弄清楚为什么你的(P2 - 蓝色)结果显示出来。我重新编写了你的​​样本作为SQL,并创建了我认为你想要的东西(等待你的预期输出),而我只生成一行(P1 - 红色)

create table dbo.Product (
    ProductID int not null,
    Name char(2) not null,
    StateId char(2) not null,
    CityId char(2) not null,
    CountryId char(2) not null,
    Price int not null,
    Colour varchar(10) not null,
    constraint PK_Product PRIMARY KEY (ProductID)
)
go
insert into dbo.Product (ProductID,Name,StateId,CityId,CountryId,Price,Colour)
select 1,'P1','S1','C1','C1',150,'Red' union all
select 2,'P2','S2','C2','C1',100,'Blue' union all
select 3,'P3','S1','C3','C1',200,'Green'
go
create table dbo.Settings (
    SettingsID int not null,
    StateId char(2) null,
    CityId char(2) null,
    CountryId char(2) null,
    MaxPrice int not null,
    MinPrice int not null,
    constraint PK_Settings PRIMARY KEY (SettingsID)
)
go
insert into dbo.Settings (SettingsID,StateId,CityId,CountryId,MaxPrice,MinPrice)
select 1,null,null,'C1',1000,150 union all
select 2,'S1',null,'C1',2000,100 union all
select 3,'S1','C3','C1',3000,300
go

现在是实际观点:

create view dbo.Products_Filtered
with schemabinding
as
    with MatchedSettings as (
    select p.ProductID,MAX(MinPrice) as MinPrice,MIN(MaxPrice) as MaxPrice
    from
        dbo.Product p
            inner join
        dbo.Settings s
            on
                (p.CountryId = s.CountryId or s.CountryId is null) and
                (p.CityId = s.CityId or s.CityId is null) and
                (p.StateId = s.StateId or s.StateId is null)
    group by
        p.ProductID
    )
    select
        p.ProductID,p.Name,p.CityID,p.StateId,p.CountryId,p.Price,p.Colour
    from
        dbo.Product p
            inner join
        MatchedSettings ms
            on
                p.ProductID = ms.ProductID and
                p.Price between ms.MinPrice and ms.MaxPrice

我所做的是组合所有适用的设置,然后假设我们应用了最严格的设置(因此请指定MAX MinPrice和MIN MaxPrice)。

使用这些规则,排除了(P2 - 蓝色)行,因为唯一适用的设置是设置1 - 最低价格为150.

如果我将其反转,以便我们尝试尽可能包容(MIN MinPrice和MAX MaxPrice),那么返回(P1 - 红色)和(P3 - 绿色) - 但仍然不是(P2 - 蓝色)< / p>