簡體   English   中英

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

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

我想找到col1中col2記錄的條目。

表:

CREATE TABLE Test_Table
(
    Col1 int,
    Col2 int
);

項:

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

預期結果:

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

注意:記錄114,115未顯示,因為col1不存在115

我的嘗試:

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;

但獲得所有記錄。

我想這就是你想要的。

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
             );

這也可能有用

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

我想你只想exists

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

使用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 

根據你的評論,我懷疑你想要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