7

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?

4

6 回答 6

26

尝试这个:

SELECT table1.*
FROM table1
LEFT OUTER JOIN table2
ON table1.id = table2.id
WHERE table2.id IS NULL

LEFT OUTER JOIN链接从table1开始的两个表,如果table2没有链接行,table2的所有字段都将为空。所以,如果你把你的WHERE条件 table2.id 设置为空,你只会得到 table1 中不存在于 table2 中的行

于 2013-08-01T12:57:30.243 回答
3

您可以通过执行左外连接并检查所有不存在的行来解决此问题。根据您是否要查找表 2 中的表 1 或表 1 中的表 2 中不存在的值,请尝试以下操作。

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 小提琴:http ://sqlfiddle.com/#!2/a9390/8

于 2013-08-01T12:51:54.160 回答
1

使用此查询:

SELECT 
    * 
FROM 
    table2 
LEFT JOIN 
    table1
ON 
    table2.primary_key = table1 .primary_key
WHERE 
    table1 .primary_key IS NULL
;
于 2013-08-01T13:03:48.530 回答
1

好吧,如果您想要 PHP 中的答案,那么就是:

$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>";
    }
}

我希望这对你有帮助

于 2013-08-01T13:15:59.297 回答
0

如果您想按所有列比较 2 个表(完全比较,而不仅仅是按 ID 等单个特定列),您可以使用这种方法:

SELECT column1, column2, column3
FROM
 (
   SELECT t1.column1, t1.column2, t1.column3
   FROM t1
   UNION ALL
   SELECT t2.column1, t2.column2, t2.column3
   FROM t2
)  t
GROUP BY column1, column2, column3
HAVING COUNT(*) = 1
ORDER BY column3

基于示例:http ://www.mysqltutorial.org/compare-two-tables-to-find-unmatched-records-mysql.aspx

于 2018-11-06T15:16:53.120 回答
0
SELECT * FROM table1
where id not in (
    SELECT table2.id
    FROM table2
    LEFT OUTER JOIN table1
    ON (
        table1.id = table2.id 
        and table1.col1 = table2.col1 
        and table1.col2 = table2.col2
        ...
    )
)

那里table1table2有更多的行

于 2020-06-20T11:12:24.260 回答