MySQL 如何在两个MySQL表中比较数据?
有时,我们需要从两个表中识别未匹配的数据,特别是在数据迁移的情况下。通过比较表,可以实现这一点。考虑下面的示例,其中我们有两个名为“students”和“student1”的表。
mysql> Select * from students;
+--------+--------+----------+
| RollNo | Name | Subject |
+--------+--------+----------+
| 100 | Gaurav | Computer |
| 101 | Raman | History |
| 102 | Somil | Computer |
+--------+--------+----------+
3 rows in set (0.00 sec)
mysql> select * from student1;
+--------+--------+----------+
| RollNo | Name | Subject |
+--------+--------+----------+
| 100 | Gaurav | Computer |
| 101 | Raman | History |
| 102 | Somil | Computer |
| 103 | Rahul | DBMS |
| 104 | Aarav | History |
+--------+--------+----------+
5 rows in set (0.00 sec)
现在,借助下面的查询,我们可以比较这些表,并将未匹配的行作为结果集。
mysql> Select RollNo,Name,Subject from(select RollNo,Name,Subject from students union all select RollNo,Name,Subject from Student1)as std GROUP BY RollNo,Name,Subject HAVING Count(*) = 1 ORDER BY RollNo;
+--------+-------+---------+
| RollNo | Name | Subject |
+--------+-------+---------+
| 103 | Rahul | DBMS |
| 104 | Aarav | History |
+--------+-------+---------+
1 rows in set (0.02 sec)
阅读更多:MySQL 教程