Lad os først og fremmest prøve at se fordele og ulemper ved hver af 2 tilgange:
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;
Den første er bedre, når du bruger den i joins, især hvis du ikke vil bruge alle dine kolonner. Lad os f.eks. sige, at du har udsigt, når du bruger din 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;
Nu, hvis du ønsker at gøre enkelt, vælg:
select Name from vw_people1;
select Name from vw_people2;
Den første ville være simpelt at vælge fra people
(vw_Car1
vil slet ikke blive spurgt). Den anden vil være mere kompleks - Ford
og Chevy
vil begge blive forespurgt. Du kunne tro, at den første tilgang er bedre, men lad os prøve en anden forespørgsel:
select *
from vw_people1
where Maker = 'Ford' and Model = 'Fiesta';
select *
from vw_people2
where Maker = 'Ford' and Model = 'Fiesta';
Her vil den anden være hurtigere, især hvis du har indeks på Model
kolonne.
=> sql violindemo - se forespørgselsplaner for disse forespørgsler.