2012-10-17 49 views
1

我試圖創建一個SQL視圖,它合併了一些單獨的選擇查詢。我遇到了一些困難,從單個select語句的子句放入數據庫視圖。可以在視圖中使用連接的where子句

我的觀點的簡化版本是:

create or replace view TestView as 
select 
A.Name, 
B.Subscription, 
C.Expiry 
from 
TestTableA as A left outer join TestTableB as B on A.ID = B.A_ID 
left outer join TestTableC as C on A.ID = C.A_ID; 

我有兩個問題的看法:

  • 在弗里斯特加入我怎麼可以只選擇記錄下認購一個具體的價值,如果它不是那個價值仍然檢索名稱和到期列(在這種情況下,訂閱將爲空)?

  • 第二次加入我如何指定我只想要最近到期日期的記錄?

下面是我的測試模式,樣本數據和所希望的結果集:

create table TestTableA 
(
    ID int, 
    Name varchar(32), 
    Primary Key(ID) 
); 

create table TestTableB 
(
    ID int, 
    A_ID int, 
    Subscription varchar(32), 
    Primary Key(ID), 
    Foreign Key(A_ID) references TestTableA(ID) 
); 

create table TestTableC 
(
    ID int, 
    A_ID int, 
    Expiry date, 
    Primary Key(ID), 
    Foreign Key(A_ID) references TestTableA(ID) 
); 

create or replace view TestView as 
select 
A.Name, 
B.Subscription, 
C.Expiry 
from 
TestTableA as A left outer join TestTableB as B on A.ID = B.A_ID 
left outer join TestTableC as C on A.ID = C.A_ID; 

insert into TestTableA values (1, 'Joe'); 
insert into TestTableB values (1, 1, 'abcd'); 
insert into TestTableB values (2, 1, 'efgh'); 
insert into TestTableC values (1, 1, '2012-10-25'); 
insert into TestTableC values (2, 1, '2012-10-24'); 
insert into TestTableA values (2, 'Jane'); 

期望的結果1:

select * from TestView where Subscription is null or Subscription = 'efgh'; 

Joe, efgh, 2012-10-25 
Jane, , 

期望的結果2:

select * from TestView where Subscription is null or Subscription = 'xxxx'; 

Joe, , 2012-10-25 
Jane, , 

回答

2

我將用簡單的SQL編寫查詢 如果您有SQL Server 2005或更高版本,可以使用outer apply,而不是與min()

select 
    A.Name, 
    B.Subscription, 
    C.Expiry 
from TestTableA as A 
    left outer join TestTableB as B on A.ID = B.A_ID and B.Subscription in ('abcd', 'efgh') 
    left outer join 
    (
     select min(T.Expiry) as Expiry, T.A_ID 
     from TestTableC as T 
     group by T.A_ID 
    ) as C on A.ID = C.A_ID 
0
create or replace view TestView as 
select 
    A.Name, 
    B.Subscription, 
    C.Expiry 
from 
    TestTableA as A left outer join TestTableB as B on A.ID = B.A_ID 
    left outer join TestTableC as C on A.ID = C.A_ID; 
where 
    B.Subscription is not null 
    and C.Expiry between (now() - interval 1 minute) and now() 
的子查詢加盟