Converting a self subquery to a self join

2019-06-03 02:16发布

I was wondering if there was a way to convert a self subquery to a self join Here is the self subquery

SELECT a, 
       b 
FROM   c AS t1 
WHERE  ( b IN (SELECT b 
               FROM   c AS t2 
               WHERE  ( t1.b = b ) 
                      AND ( t1.e <> e )) ) 

4条回答
淡お忘
2楼-- · 2019-06-03 02:30
SELECT t1.a, t2.b
FROM c as t1
join c as t2 on t1.b=t2.b
WHERE t1.e <> t2.e
查看更多
SAY GOODBYE
3楼-- · 2019-06-03 02:34

As e is the Primary Key another way of approaching this would be

SELECT a, 
       b 
FROM   (SELECT a, 
               b, 
               COUNT(*) OVER (PARTITION BY b) AS Cnt 
        FROM   c) T1 
WHERE  Cnt > 1 
查看更多
我想做一个坏孩纸
4楼-- · 2019-06-03 02:36
select  t1.a
,       t1.b
from    c as t1
join    c as t2
on      t1.b = t2.b 
        and t1.e <> t2.e
查看更多
Root(大扎)
5楼-- · 2019-06-03 02:43

If you only want to find the duplicates an EXIST would probably be faster:

SELECT a,b FROM c WHERE EXISTS(SELECT NULL FROM c c2 WHERE c2.b=c.b AND c2.e<>c.e) 

If you want to join every record with its duplicate but get only one record for each:

select  t1.a
,       t1.b
,       t1.e as t1e
,       t2.e as t2e
from    c as t1
inner join c as t2
on      t1.b = t2.b 
        and t1.e > t2.e

(note that i've used > instead of <>)

查看更多
登录 后发表回答