I have two tables. One table (table1) has 28500 rows and the another (table2) has 17450 rows. I would like to compare these tables and find rows that do not exist in table1.
SELECT * FROM table1 WHERE ID NOT IN (SELECT DISTINCT(ID) FROM table2)
Any suggestions?
Replace database_name_1 and database_name_2 with names of two of your databases (schemas) (on MySQL instance) that you'd like to compare. database1 - if column exists in a table in database1 (schema) then column contains its name (repeats it from column column)
Similarly, here’s how to compare two tables to find unmatched columns in MySQL. In the above query, instead of using count (*)>1, we use the condition count (*)=1, that is records that occur only once. Here’s the SQL to compare two tables and find records without matches.
First, use the UNION statement to combine rows in both tables; include only the columns that need to compare. The returned result set is used for the comparison. Second, group the records based on the primary key and columns that need to compare.
Here’s the SQL query to compare two columns from different tables and select records that match. In the above query, we select records from orders whose id column value is present in the list of id column values obtained from orders2 using a subquery.
Try this:
SELECT table1.*
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
WHERE table2.id IS NULL
LEFT OUTER JOIN
link two table starting by table1, if table2 has no linked row all fields of table2 will be null. So, if you put in your WHERE
condition table2.id is null, you get only rows in table1 not existing in table2
You could solve this by doing a left outer join and checking for all rows that don't exist. Try the following depending on if you want to find values not existent from table1 in table2 or table2 in table1.
SELECT *
FROM table1
LEFT OUTER JOIN table2 ON (table1.id = table2.id)
WHERE table2.id IS NULL;
SELECT *
FROM table2
LEFT OUTER JOIN table1 ON (table1.id = table2.id)
WHERE table2.id IS NULL;
SQL Fiddle: http://sqlfiddle.com/#!2/a9390/8
Make use of this query:
SELECT
*
FROM
table2
LEFT JOIN
table1
ON
table2.primary_key = table1 .primary_key
WHERE
table1 .primary_key IS NULL
;
well, if you want the answer in PHP, then here is it:
$sql=mysql_query("SELECT * FROM table1");
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$sql2=mysql_query("SELECT * FROM table2 WHERE id='$id'");
$check=mysql_num_rows($sql2);
if($check==0)
{
echo $id." is not in table1<br>";
}
}
I hope this help you
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With