Sql 在两列中查找具有相同值的行
我在Postgres数据库中有3列,其中有表mytable,我希望记录在第2列和第3列中只有重复的值Sql 在两列中查找具有相同值的行,sql,postgresql,Sql,Postgresql,我在Postgres数据库中有3列,其中有表mytable,我希望记录在第2列和第3列中只有重复的值 SQL> select * from mytable ; column1 column2 column3 A 1 50----required output ie. 50 is duplicate in line B column 2 B 50 3 ----require
SQL> select * from mytable ;
column1 column2 column3
A 1 50----required output ie. 50 is duplicate in line B column 2
B 50 3 ----required output ie. 50 is duplicate in line A column 3
C 2 10----values are duplicate in others lines
D 30 70----required output ie. 30 is duplicate in line E column 3
E 8 30----required output ie. 30 is duplicate in line D column 2
F 40 25----values are not duplicate in others lines
我想要以下带有count(*)的输出:
以下是处理此问题的自联接示例:
select distinct m.*
from mytable m
inner join mytable m2
on (
m.column2 in (m2.column2, m2.column3)
or m.column3 in (m2.column2, m2.column3)
)
and m.column1 <> m2.column1
选择distinct m*
从我的表m
内部联接表m2
在(
m、 柱2英寸(m2.column2,m2.column3)
或m.column3英寸(m2.column2,m2.column3)
)
和m.column1 m2.column1
我会使用存在
:
select t.*
from mytable t
where exists (select 1
from mytable t2
where t.col2 in (t2.col2, t2.col3) or
t.col3 in (t2.col2, t2.col3)
);
select t.*
from mytable t
where exists (select 1
from mytable t2
where t.col2 in (t2.col2, t2.col3) or
t.col3 in (t2.col2, t2.col3)
);