2013-10-21 30 views
0

我在SQL Server 2008 R2數據庫中有兩個表。我想創建一個視圖,其中包含Table1中的所有列,並接收附加的名爲「Photo_Exist」的附加列,如果Table1中存在ID,則分配「1」或「True」。將值設置爲其ID存在於另一個表中的行上的列

表1: ID中,col1,col2的,...,科隆

表2: Linked_ID

查看: ID中,col1,col2的,...,科隆,Photo_Exist

在此先感謝!

亞歷

回答

2

試試這個

SELECT *, 
     CASE WHEN EXISTS (SELECT * FROM Table2 AS T2 WHERE T2.Linked_ID=T1.ID) 
      THEN 1 
      ELSE 0 
     END AS Photo_Exist 
FROM Table1 AS T1 
1

創建使用此查詢的視圖。這應該有幫助

select table1.*, case when table2.linked_id is null then 0 else 1 end as Photo_exist 
    from table1 left outer join table2 on table1.id =table2.linked_id 
+1

+1但是你要記住,如果有對應的''中Table1' ID'多個'Linked_ID'在'Table2'比你的結果與同一組得到幾行' ID'。 –

1

我喜歡使用子查詢這種類型的東西。

select 
    t1.*, 
    Photo_Exists = 
     case 
      when t2.Linked_ID is null then 0 
      else 1 
     end 
from Table1 t1 
    left join 
    (
     select distinct 
      Linked_ID 
     from Table2 
    ) t2 on t1.ID = t2.Linked_ID 
相關問題