有時我們需要找出兩個表中不匹配的數據,尤其是在數據遷移的情況下。可以通過比較表格來完成。考慮下面的示例,其中我們有兩個名為“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 表中的數據?的詳細內容,更多請關注www.92cms.cn其它相關文章!