Converting a self subquery to a self join

半世苍凉 提交于 2019-12-10 11:41:28

问题


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

回答1:


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




回答2:


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 



回答3:


SELECT t1.a, t2.b
FROM c as t1
join c as t2 on t1.b=t2.b
WHERE t1.e <> t2.e



回答4:


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


来源:https://stackoverflow.com/questions/9762390/converting-a-self-subquery-to-a-self-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!