![](/img/trans.png)
[英]Select rows from a table where row in another table with same id has a particular value in another column
[英]Set value to a column on the row where its ID exists in another table
我在SQL Server 2008 R2数据库中有两个表。 我想创建一个视图,在其中具有表1中的所有列,并接收附加到其的附加列“ Photo_Exist”,如果表2中存在表1中的ID,则将其分配为“ 1”或“真”。
表1 :ID,Col1,Col2,...,Coln
表2 :Linked_ID
查看 :ID,Col1,Col2,...,Coln,Photo_Exist
提前致谢!
亚历克斯
尝试这个
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
使用此查询创建视图。 这应该有帮助
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
我喜欢对这种类型的东西使用子查询。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.