T-SQL查询,仅显示一列中的值与另一行中另一列中的值匹配的行

时间:2018-05-09 11:27:31

标签: sql-server tsql

我已经用尽了对tsql的有限知识,我希望有人可以提供帮助吗?

我有一个表格,其中包含关系数据,例如ID,姓名,关系和互惠关系类型,开始和结束日期等。

每行包含关系另一侧的倒数ID。见下文。

由此我想呈现ID等于1234和1236的行。

提前感谢您的帮助。

+------+-------+------------+------------+----------+------------+---------+
| ID   | Name  | Start      | Finish     | Type     | Recip Type | RecipID |
+------+-------+------------+------------+----------+------------+---------+
| 1234 | Joe   | 01/05/2018 |            | Father   | Daughter   | 1235    |
+------+-------+------------+------------+----------+------------+---------+
| 1235 | Emily | 01/05/2018 |            | Daughter | Father     | 1234    |
+------+-------+------------+------------+----------+------------+---------+
| 1236 | Susan | 01/09/2017 | 01/05/2018 | Visitor  | Patient    | 1237    |
+------+-------+------------+------------+----------+------------+---------+
| 1237 | Harry | 01/09/2017 | 01/05/2018 | Patient  | Visitor    | 1236    |
+------+-------+------------+------------+----------+------------+---------+

2 个答案:

答案 0 :(得分:0)

您在寻找or

select t.*
from t
where id in (1234, 1236) or recipid in (1234, 1236);

答案 1 :(得分:0)

也许这会做你想要的事情:

select t1.* 
from table t1 
where exists (select 1 from table t2 where t1.id = t2.recipid);

然而,同样可以通过self join

实现