简体   繁体   中英

Oracle query where field1=field2 and field2=field1

So I have a table that holds a link relationship. Field1 is and ID and Filed2 is an ID. So far I've eliminated duplicate Field1\\Field2 combinations. However I still have cases where the inverse occurs. Meaning Field1 occurs as Field2 and Field2 occurs in Field1 for the same record. I tried a subquery within in inner join but it's returning way to many rows. Thanks in advance!

select a.field1, a.field2 from linktable
inner join (select field1, field2 from linktable) b on a.field1=b.field2 and a.field2=b.field1;

Sample data:

insert into linktable(field1, field2) values ('ABC', '123');
insert into linktable(field1, field2) values ('123', 'ABC');

I want to identify and remove cases where the above sample data occurs.

Something like this should get you the pairs:

SELECT a.field1, a.field2
  FROM linktable a
  JOIN linktable b ON (b.field1 = a.field2 AND b.field2 = a.field1)

Edit: An example of finding one of the pairs:

create table linktable(id number, field1 varchar2(32), field2 varchar2(32));
insert into linktable(id, field1, field2) values (1, 'ABC', '123');
insert into linktable(id, field1, field2) values (2, '123', 'ABC');

SELECT a.field1, a.field2, LEAST(a.id, b.id) AS id_to_delete
  FROM linktable a
  JOIN linktable b ON (b.field1 = a.field2 AND b.field2 = a.field1);

Result:

FIELD1  FIELD2  ID_TO_DELETE
123     ABC     1
ABC     123     1

Is this what you want?

select field1, field2
from (select field1, field2, 
             row_number() over (partition by least(field1, field2), greatest(field1, field2) order by field1) as seqnum
      from t
     ) t
where seqnum = 1;

This returns one instance of field1 / field2 regardless of ordering.

You should post sample data and expected result.

I think this query may work for you, this prevent the inverse occurs as field1, field2 = (x, y) and (y, x)

SELECT field1, field2 
FROM linktable
WHERE field1 >= field2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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