1

我有以下通用表结构(在我的人为示例中,请原谅以美国为中心的汽车制造商):

CREATE TABLE Car (
    [Id] int PRIMARY KEY
)

CREATE TABLE Ford (
    [FordId] int PRIMARY KEY, --also a foreign key on Car
    [Model]  nvarchar(max)
)

CREATE TABLE Chevy (
    [ChevyId] int PRIMARY KEY, --also a foreign key on Car
    [Model]  nvarchar(max)
)

我想在这些表上创建一个视图,以便我可以检索所有福特和雪佛兰,并在视图中生成一个告诉我品牌的列。我的第一个刺是这样的:

SELECT 
    c.CarId,
    case when f.FordId is not null then 'Ford' else 'Chevy' end 
FROM Car as c
LEFT JOIN Ford as f on c.Id = f.FordId
LEFT JOIN Chevy as ch on c.Id = ch.ChevyId
WHERE (f.FordId is not null or ch.ChevyId is not null)

但这在我嘴里留下了不好的味道,我担心性能。以不同的 CTE 值检索所有福特和雪佛兰,然后对它们执行联合,我会更好吗?我完全走错了吗?我还需要包含 Model 列(以及两个子表共有的其他一些列),这显然会使我的视图变成一系列巨大的案例陈述。处理这种情况的“正确”方法是什么?

编辑:我想我应该补充一点,这个模式已经存在,所以改变基础表是不可能的。

4

1 回答 1

1

首先,让我们尝试看看两种方法的优缺点:

create view vw_Car1
as
  SELECT 
      c.Id,
      case when f.FordId is not null then 'Ford' else 'Chevy' end as Maker,
      coalesce(f.Model, ch.Model) as Model
  FROM Car as c
  LEFT JOIN Ford as f on c.Id = f.FordId
  LEFT JOIN Chevy as ch on c.Id = ch.ChevyId
  WHERE (f.FordId is not null or ch.ChevyId is not null);

create view vw_Car2
as
  select FordId as id, 'Ford' as Maker, Model from Ford
  union all
  select ChevyId as id, 'Chevy' as Maker, Model from Chevy;

当您在连接中使用第一个时会更好,特别是如果您不会使用所有列。例如,假设您在使用时有一个视图vw_Car

create table people (name nvarchar(128), Carid int);

insert into people
select 'John', 1 union all
select 'Paul', 2;

create view vw_people1
as
select
    p.Name, c.Maker, c.Model
from people as p
   left outer join vw_Car1 as c on c.ID = p.CarID;

create view vw_people2
as
select
    p.Name, c.Maker, c.Model
from people as p
   left outer join vw_Car2 as c on c.ID = p.CarID;

现在,如果你想做简单的选择:

select Name from vw_people1;

select Name from vw_people2;

第一个是简单的 select from peoplevw_Car1根本不会被查询)。第二个会更复杂 -Ford并且Chevy都会被查询。您可能认为第一种方法更好,但让我们尝试另一个查询:

select *
from vw_people1
where Maker = 'Ford' and Model = 'Fiesta';

select *
from vw_people2
where Maker = 'Ford' and Model = 'Fiesta';

这里第二个会更快,特别是如果您在Model列上有索引。

=> sql fiddle demo - 查看这些查询的查询计划。

于 2013-09-06T16:49:35.260 回答