如何比较两个 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)
广告