Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql select query in same table

Tags:

sql

select

i have a newby sql related question.

let's say i have this simple table:

A      B
------ ------
a      b
a      c
b      a
m      n
m      o
n      m

i'd like to query for records which have "counterparts" only, i.e. i want to get a b only if there is b a in the table but i want to skip the "back links" (which is b ahere). to sum up i'd like to get the following result

A       B
------  ------
a       b
m       n

this sql query does not work since in the case b a is handled the a b is removed from my result set.

SELECT DISTINCT x1.A, x1.B
FROM TEST x1, TEST x2
WHERE x1.A = x2.B AND x1.B = x2.A -- all records /w counterparts only
AND x1.A NOT IN (SELECT B from TEST where B = x1.A) -- skip the "back links"

the 2nd part of the WHERE clause does not work as desired.

do you have any hints? any help with this would be greatly appreciated.

regards peter

p.s. i am using the derby db.

like image 293
D. Manka Avatar asked Nov 21 '12 15:11

D. Manka


People also ask

How do I join two SELECT statements in the same table in SQL?

To combine two or more SELECT statements to form a single result table, use the set operators: UNION, EXCEPT or INTERSECT.

Can we use SELECT * with group by?

You can use a SELECT command with a GROUP BY clause to group all rows that have identical values in a specified column or combination of columns, into a single row.

Is it possible to use the same table twice in a SELECT query?

You use a single table twice in a query by giving it two names, like that. The aliases are often introduced with the keyword AS. You also normally specify a join condition (for without it, you get the Cartesian Product of the table joined with itself). For preference you use the explicit JOIN notation.

Can we apply join on same table?

You use self-join to create a result set that joins the rows with the other rows within the same table. Because you cannot refer to the same table more than one in a query, you need to use a table alias to assign the table a different name when you use self-join.


1 Answers

You could change your last line to:

AND x1.A < x1.B

This assumes that either your columns are never self-referential (eg: a, a) or that you don't want circular references to appear. If you do, then:

AND x1.A <= x1.B

EDIT:

You're probably better off using explicit joins as well:

SELECT DISTINCT 
    x1.A
    , x1.B
FROM 
    TEST x1
JOIN 
    TEST x2
    ON x1.A = x2.B 
        AND x1.B = x2.A -- all records /w counterparts only
WHERE x1.A < x1.B --Skip backreference
like image 176
JAQFrost Avatar answered Sep 24 '22 13:09

JAQFrost