繁体   English   中英

在SQL Server中,如何从另一个表的匹配的*两*列中选择所有内容?

[英]In SQL Server, How Do I Select All the Things From Another Table's Matching *TWO* Columns?

注意:如果您可以找到一个更好的标题此问题的方法,请对其进行编辑。 这很难说出来。

因此,假设包含以下内容的Stuff表:

Stuff
=====
Id, Col1ThingId, Col2ThingId, 

和相关的事物表

Things
======
Id, Name, Rank, Whatever

我想检索所有匹配要么 Col1ThingId或Col2ThingId的事情。 我可以选择具有ID的资料:

SELECT Col1ThingId, Col2ThingId
FROM STUFF
WHERE Id = 15

这给了我这个结果:

Col1ThingId Col2ThingId
41472       41474
41510       41512
41513       41515

因此,我正在尝试获取所有这六样东西。 就像是:

Select *
from Things 
where Id "is contained in either column of" {
   select Col1ThingId, Col2ThingId 
   from Stuff
   where Id  = 15
}

我认为您正在使这一过程变得比所需的复杂。 您可以在此处轻松添加第二个连接谓词。

select *
from Things t
join Stuff s on s.Col1ThingId = t.Id or s.Col2ThingId = t.Id
where s.Id = 15
select *
from Stuff s
join Things t on t.id in (s.Col1ThingId, s.Col2ThingId)
where s.Id = 15
SELECT Col1ThingId
FROM STUFF
WHERE Id = 15
UNION
SELECT Col2ThingId
FROM STUFF
WHERE Id = 15;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM