Hasitha Shan
Hasitha Shan

Reputation: 2980

Find non-duplicate records from multiple tables

I searched though the internet but could not found what i was looking for, may be because i dont know what to search.

My problem is to get non-duplicate records from multiple tables...

Say if i have two tables as follows,

tableA
----------------------
code    ip
1       111.168.1.2
2       111.222.333.333
3       111.168.1.2
4       111.234.2.44
5       111.23.455.44

tableB
----------------------
code    ip                 ISP
1       111.222.333.333    newtwo
2       111.168.2.2        anon
3       111.333.453.567    def
4       111.168.2.2        tele
5       111.222.333.333    new
6       111.333.544.3      ispnew

What i expect to get out of this is,

ip
111.234.2.44
111.23.455.44
111.333.453.567
143.333.544.3

I have tried UNION, DISTICNT and DISTINCT AND UNION together like so,

SELECT DISTINCT IP FROM(SELECT IP FROM tableA UNION SELECT IP FROM tableB)

But it gives all the values unique an duplicate as follows,

ip
111168.1.2
111.222.333.333
111.234.2.44
111.23.455.44
111.168.2.2 
111.333.453.567     
111.333.544.3 

Please help me on this one, I will be much great-full..THANK YOU VERY MUCH :)

Upvotes: 0

Views: 3065

Answers (1)

oezi
oezi

Reputation: 51817

DISTINCT give every entry just once but doesn't throw out the duplicate ones completely. what you'll have to to is using GROUP BY, COUNT and HAVING to get rid of those:

SELECT
  IP
FROM
  (
    SELECT IP FROM tableA
  UNION ALL
    SELECT IP FROM tableB
  )
GROUP BY
  IP
HAVING
  COUNT(*) = 1

Upvotes: 4

Related Questions