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