简体   繁体   English

SQL Server 2008 R2:查找column1中存在column2值的行

[英]SQL Server 2008 R2: Find rows where column2 value present in column1

I want to find the entries where col2 record present in col1. 我想找到col1中col2记录的条目。

Table: 表:

CREATE TABLE Test_Table
(
    Col1 int,
    Col2 int
);

Entries: 项:

INSERT INTO Test_Table VALUES(111,112),
                              (112,113),
                              (114,115),
                              (116,117),
                              (117,118),
                              (118,119);

Expected Result: 预期结果:

Col1    Col2
-------------
111     112
112     113
116     117
117     118
118     119

Note: Record 114,115 not displyed because 115 is not present in col1 . 注意:记录114,115未显示,因为col1不存在115

My try: 我的尝试:

WITH CTE1
AS
(
    SELECT Col1, Col2
    FROM Test_Table
),
CTE2
AS
(
    SELECT t.Col1, t.Col2
    FROM Test_Table t
    INNER JOIN CTE1 s1
    ON s1.Col2 = t.Col1
    OR s1.Col2 = t.Col2
)
SELECT DISTINCT * FROM CTE2;

But getting all records. 但获得所有记录。

I think this is what you want. 我想这就是你想要的。

select t.*
from #test_table t
where exists (select 1
              from #test_table t2
              where t2.col1 = t.col2
             )
   or exists (select 1
              from #test_table t3
              where t3.col2 = t.col1
             );

This might also work 这也可能有用

select t.* 
from   Test_Table t
where  exists (select 1
               from   test_table t2
               where  t2.col1 = t.col2 or t2.Col2 = t.Col1
              )

I think you just want exists : 我想你只想exists

select tt.*
from test_table tt
where exists (select 1
              from test_table tt2
              where tt2.col1 = tt.col2
             );

Using CROSS JOIN : 使用CROSS JOIN

select t1.* from test_table t1 CROSS JOIN test_table t2
on t1.col1 = t2.col2 
UNION 
select t1.* from test_table t1 CROSS JOIN test_table t2
on t1.col2 = t2.col1 

Based on your comments, I suspect you want either col1/col2 to exist at another row's either col1/col2 根据你的评论,我怀疑你想要col1 / col2存在于另一行的col1 / col2

select tt.*
from test_table tt
where exists (select 1
              from test_table tt2
              where   -- Ensure not same row
                    (tt2.col1 <> tt.col1 or tt2.col2 <> tt.col2)
                and -- Ensure at least one match
                    (tt2.col1 = tt.col1 or tt2.col1 = tt.col2 or tt2.col2 = tt.col1 or tt2.col2 = tt.col2)
             );
select t1.* from Test_Table t1 left join Test_Table t2 on t2.Col1=t1.Col2 where t2.Col2 is not null
union
select t1.* from Test_Table t1 left join Test_Table t2 on t2.Col2=t1.Col1 where t2.Col1 is not null

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

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