Re: How can I selet rows which have 2 columns values cross equal?

From: Michael Glaesemann <grzm(at)myrealbox(dot)com>
To: "Fay Du" <fay(dot)du(at)versaterm(dot)com>
Cc: <pgsql-sql(at)postgresql(dot)org>
Subject: Re: How can I selet rows which have 2 columns values cross equal?
Date: 2006-03-11 07:46:29
Message-ID: B0FA7B5C-3766-478E-BDFD-CADC21B2AA0B@myrealbox.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql


On Mar 10, 2006, at 22:24 , Fay Du wrote:

> I want to get row 1, 2,4 and 7 selected. Because their values of a
> and b
> are cross equal. i.e., for each pair of rows,
> a.Row1 = b.Row2 and b.Ro1 = a.Row2
> a.Row4 = b.Row7 and b.Ro4 = a.Row7

You need to use subqueries:

create table test
(
id integer primary key
, a integer not null
, b integer not null
);

copy test (id, a, b) from stdin;
1 100 101
2 101 100
3 100 3
4 20 30
5 11 13
6 3 33
7 30 20
\.

select t1.id as t1_id, t2.id as t2_id
from test t1
join test t2 on (t1.a = t2.b and t1.b = t2.a);
t1_id | t2_id
-------+-------
7 | 4
4 | 7
2 | 1
1 | 2
(4 rows)

And if you don't want to have each pair listed twice, just add WHERE
t1.a < t2.a, e.g.,

select t1.id as t1_id, t2.id as t2_id
from test t1
join test t2 on (t1.a = t2.b and t1.b = t2.a)
where t1.a < t2.a;
t1_id | t2_id
-------+-------
4 | 7
1 | 2
(2 rows)

Hope this helps!

Michael Glaesemann
grzm myrealbox com

In response to

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Michael Glaesemann 2006-03-11 09:35:04 Re: How can I selet rows which have 2 columns values cross equal?
Previous Message Michael Fuhr 2006-03-11 06:33:08 Re: Locking row