# 比较表

在本教程中，您将学习如何比较两个表以找到不匹配的记录。

在数据迁移中，我们经常需要比较两个表，以便在一个表中标识另一个表中没有相应记录的记录。

例如，我们有一个新的数据库，其架构与旧数据库不同。我们的任务是将所有数据从旧数据库迁移到新数据库，并验证数据是否正确迁移。

要检查数据，我们必须比较两个表，一个在新数据库中，一个在旧数据库中，并标识不匹配的记录。

假设有两个表：`t1`和`t2`。使用以下步骤比较两个表，并确定不匹配的记录：

**首先**，使用[UNION语句](http://www.yiibai.com/sql-union-mysql.html)来组合两个表中的行; 仅包含需要比较的列。返回的结果集用于比较。

```sql
SELECT t1.pk, t1.c1
FROM t1
UNION ALL
SELECT t2.pk, t2.c1
FROM t2
```

**第二步**，根据需要比较的[主键](http://www.yiibai.com/mysql/primary-key.html)和列分组记录。如果需要比较的列中的值相同，则`COUNT(*)`返回`2`，否则`COUNT(*)`返回`1`。

请参阅以下查询：

```sql
SELECT pk, c1
FROM
 (
   SELECT t1.pk, t1.c1
   FROM t1
   UNION ALL
   SELECT t2.pk, t2.c1
   FROM t2
)  t
GROUP BY pk, c1
HAVING COUNT(*) = 1
ORDER BY pk
```

如果比较中涉及的列中的值相同，则不返回任何行。

## MySQL比较两个表的例子

我们来看一个模拟上述步骤的例子。

首先，创建具有相似结构的`2`个表：

```sql
USE testdb;
CREATE TABLE t1(
 id int auto_increment primary key,
    title varchar(255) 
);

CREATE TABLE t2(
 id int auto_increment primary key,
    title varchar(255),
    note varchar(255)
);
```

其次，在`t1`和`t2`表中插入一些数据：

```sql
INSERT INTO t1(title)
VALUES('row 1'),('row 2'),('row 3');

INSERT INTO t2(title,note)
SELECT title, 'data migration'
FROM t1;
```

**第三**，比较两个表的`id`和`title`列的值：

```sql
SELECT id,title
FROM (
    SELECT id, title FROM t1
    UNION ALL
    SELECT id,title FROM t2
) tbl
GROUP BY id, title
HAVING count(*) = 1
ORDER BY id;
```

没有行返回，因为没有不匹配的记录。

**第四**，在`t2`表中插入一行：

```sql
INSERT INTO t2(title,note)
VALUES('new row 4','new');
```

没有行返回，因为没有不匹配的记录。

**第四步**，在`t2`表中插入一行：…

```sql
INSERT INTO t2(title,note)
VALUES('new row 4','new');
```

**第五步**，执行查询以再次比较两个表中的`title`列的值。新行是不匹配的行将会返回。

```sql
mysql> SELECT id,title
FROM (
    SELECT id, title FROM t1
    UNION ALL
    SELECT id,title FROM t2
) tbl
GROUP BY id, title
HAVING count(*) = 1
ORDER BY id;
+----+-----------+
| id | title     |
+----+-----------+
|  4 | new row 4 |
+----+-----------+
1 row in set
```

在本教程中，您已经学习了如何根据特定列比较两个表以找到不匹配的记录。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://hezhiqiang-book.gitbook.io/mysql/di-er-zhang/bi-jiao-biao.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
