Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two columns to get data that doesn't same

Tags:

sql

mysql

I wanna compare 2 tables to get data that doesn't same.

tb1              tb2
==============   ==============
|id| doc_name|   |id| doc_summ|
==============   ==============
|1 | 01180543|   |1 | 01180543|
|2 | Chord   |   ============== 
============== 

I wanna compare doc_name and doc_summ. from that example the result must be Chord.

$q = mysql_query(" SELECT t1.doc_name FROM tb1 as t1, tb2 as t2 WHERE t1.doc_name != t2.doc_summ");
while ($row = mysql_fetch_array($q)){
    $doc_copy = $row['doc_name'];
}

but the result still returns all of data. what's wrong? thank you :)

like image 813
bruine Avatar asked Aug 01 '26 21:08

bruine


2 Answers

You can join both tables using LEFT JOIN. What it does is it only display the records of table 1 if it has no match on table 2.

SELECT  a.*
FROM    tb1 a
        LEFT JOIN tb2 b
            ON a.doc_name = b.doc_summ
WHERE   b.doc_summ IS NULL
  • SQLFiddle Demo
like image 174
John Woo Avatar answered Aug 04 '26 12:08

John Woo


Try this:

SELECT t1.doc_name 
FROM   t1 
WHERE  NOT EXISTS(SELECT t2.doc_summ 
                  FROM   t2 
                  WHERE  t2.doc_summ = t1.doc_name) 

The mistake in your query is that you are joining two table, so you will always find a row in t2 which would not satisfy the where condition therefore displaying all data.

DEMO

like image 35
Ankur Avatar answered Aug 04 '26 12:08

Ankur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!