Home  >  Article  >  Backend Development  >  PHP compares different data from two tables

PHP compares different data from two tables

angryTom
angryTomOriginal
2019-10-31 16:02:583483browse

PHP compares different data from two tables

PHP compares different data in two tables

SQL statement to compare table data:

(select *
        from EMP
        minus
        select *from EMP2)
union 
(select *
       from EMP2
       minus
       select * from EMP)

Note: The premise is that the table structure is the same, you can perform data difference query

The following results are obtained:

PHP compares different data from two tables

Result: The difference between the two tables with the same structure is obtained Data

But it is impossible to distinguish which row of data belongs to which table, so a subquery is added and the virtual column name is used to distinguish. The sql is as follows:

select a.*,'EMP' from (select *
          from EMP
        minus
        select * FROM EMP2)  a
        
union 
select b.*,'EMP2' from
(select *
         from EMP2
       minus
       select * FROM EMP) b

The obtained query The result is as follows:

PHP compares different data from two tables

Result: EMP line is added to distinguish;

Finally, use php to implement it:

<?php
$serve = &#39;localhost:3306&#39;;
$username = &#39;root&#39;;
$password = &#39;admin123&#39;;
$dbname = &#39;examples&#39;;
$link = mysqli_connect($serve,$username,$password,$dbname);
mysqli_set_charset($link,&#39;UTF-8&#39;); // 设置数据库字符集
$result = mysqli_query($link,"select a.*,&#39;EMP&#39; from (select * from EMP minus select * FROM EMP2) a union select b.*,&#39;EMP2&#39; from (select * from EMP2 minus select * FROM EMP) b");
while ($row = mysqli_fetch_assoc($result)) {   

}
?>

For more PHP related knowledge, please visit PHP Chinese website!

The above is the detailed content of PHP compares different data from two tables. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn