0

I have two tables t1 and t2 as following

t1

A    B    C    D   E
1    2    c    d    e
3    1    d    e    f
4    2    f    g    h

t2

A    B    
1    2    
8    6   
4    2   

Here A,B,C,D,E are the columns of t1 and A,B are the columns of t2 where A and B are common columns.
What I have done so far
I have written the following query

WITH temp as (
    select * 
    from t2
) 
select tab1.* 
from t1 tab1, temp tab2 
where (tab1.A!=tab2.A OR tab1.B!=tab2.B)

I wanted this output

A    B    C    D    E
3    1    d    e    f

But I am getting this output

A    B    C    D    E
1    2    c    d    e
1    2    c    d    e
3    1    d    e    f
3    1    d    e    f
3    1    d    e    f
4    2    f    g    h
4    2    f    g    h

What query should I use?

2 Answers 2

3

If I understand you correctly, you'd like those rows from T1 that don't have corresponding rows in T2. The easiest way in my opinion is a LEFT OUTER JOIN:

psql=> select * from t1;
 a | b | c | d | e 
---+---+---+---+---
 1 | 2 | c | d | e
 3 | 1 | d | e | f
 4 | 2 | f | g | h
(3 rows)

psql=> select * from t2;
 a | b 
---+---
 1 | 2
 8 | 6
 4 | 2
(3 rows)

psql=> select t1.a, t1.b, t1.c, t1.d, t1.e from t1 left outer join t2 on (t1.a = t2.a and t1.b = t2.b) where t2.a is null;
 a | b | c | d | e 
---+---+---+---+---
 3 | 1 | d | e | f
(1 row)

Edit: Here's the select without the where clause, with the rows from t2 added (otherwise it'd be just like a select * from t1). As you can see, the first row contains NULLs for t2_a and t2_b:

psql=> select t1.a, t1.b, t1.c, t1.d, t1.e, t2.a as t2_a, t2.b as t2_b from t1 left outer join t2 on (t1.a = t2.a and t1.b = t2.b);
 a | b | c | d | e | t2_a | t2_b 
---+---+---+---+---+------+------
 3 | 1 | d | e | f |      |     
 1 | 2 | c | d | e |    1 |    2
 4 | 2 | f | g | h |    4 |    2
(3 rows)
Sign up to request clarification or add additional context in comments.

3 Comments

It doesnt return any row :( Are u sure the query works fine? Can u tell how this query will be executed?
The paste above is from an actual psql session, so it definitely works for the test data you provided. The left outer join will add NULL instead of real data if the second table doesn't contain a matching row (based on the ON (t1.a = t2.a and t1.b = t2.b) condition).
Pardon me. It works actually. Can u please show the output after the left outer join without "t2.a is null" constraint? I am trying to understand the query.
0

How about:

SELECT * FROM t1 WHERE (a,b) NOT IN (SELECT a,b FROM t2);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.