在SQL Server中有条件地应用联接
我有一些记录集,但现在我只能从这组记录中选择在两个表中都有IR Id的记录 假设我有表1,其中包含在SQL Server中有条件地应用联接,sql,sql-server,sql-server-2012,sql-server-2008-r2,Sql,Sql Server,Sql Server 2012,Sql Server 2008 R2,我有一些记录集,但现在我只能从这组记录中选择在两个表中都有IR Id的记录 假设我有表1,其中包含 Id Name ---------- 1 Name1 2 Name2 现在我只需要从表1中选择那些记录 其id在表2中或表3中 我正在尝试应用或运算符witin内部联接,如: select * from table1 inner join table2 on table2.id = table1.id or inner join table3 on table3.id = tabl
Id Name
----------
1 Name1
2 Name2
现在我只需要从表1中选择那些记录
其id在表2中或表3中
我正在尝试应用或运算符witin内部联接,如:
select *
from table1
inner join table2 on table2.id = table1.id or
inner join table3 on table3.id = table1.id.
可能吗?最好的方法是什么?其实我也不能用
if exist(select 1 from table2 where id=table1.id) then select from table1
有人能帮我克服这一点吗 使用
左连接
,然后检查是否至少有一个连接找到了关系
select t1.*
from table1 t1
left join table2 t2 on t2.id = t1.id
left join table3 t3 on t3.id = t1.id
where t2.id is not null
or t3.is is not null
使用
左联接
,然后检查是否至少有一个联接找到了关系
select t1.*
from table1 t1
left join table2 t2 on t2.id = t1.id
left join table3 t3 on t3.id = t1.id
where t2.id is not null
or t3.is is not null
我认为最有效的方法是在表2和表3中使用
联合
,并加入其中:
SELECT t1.*
FROM table1 t1
INNER JOIN(SELECT id FROM Table2
UNION
SELECT id FROM Table3) s
ON(t.id = s.id)
我认为最有效的方法是在表2和表3中使用
联合
,并加入其中:
SELECT t1.*
FROM table1 t1
INNER JOIN(SELECT id FROM Table2
UNION
SELECT id FROM Table3) s
ON(t.id = s.id)
我倾向于使用
exists
:
select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.id = t1.id) or
exists (select 1 from table3 t3 where t3.id = t1.id) ;
与联接相比,使用
(或中的)的优点在于包含重复的行。如果table2
或table3
对于给定的id
有多行,那么使用join
的版本将在结果集中产生多行。我倾向于使用exists
:
select t1.*
from table1 t1
where exists (select 1 from table2 t2 where t2.id = t1.id) or
exists (select 1 from table3 t3 where t3.id = t1.id) ;
与联接相比,使用(或中的)的优点在于包含重复的行。如果table2
或table3
对于给定的id
有多行,则使用join
的版本将在结果集中产生多行。或者,您也可以使用以下SQL:
SELECT *
FROM dbo.Table1
WHERE id Table1.IN ( SELECT table2.id
FROM dbo.table2 )
OR Table1.id IN ( SELECT table3.id
FROM Table3 )
或者,您也可以使用以下SQL:
SELECT *
FROM dbo.Table1
WHERE id Table1.IN ( SELECT table2.id
FROM dbo.table2 )
OR Table1.id IN ( SELECT table3.id
FROM Table3 )
您完成了一半:从表1中选择*表2中的表2中的表2.id=表1.id中的表3中的表3中的表3中的表3中的表3中的表3.id=表1.id。阅读关于连接的内容:您完成了一半:从表2中的表1中选择*表2.id=表3中的表1.id中的表3中的表1.id。阅读关于连接的内容: