将逐行和每行列表与另一个表进行比较

时间:2015-03-27 03:11:17

标签: php mysql mysqli

我有两张具有相同结构的表格。 (参见下文)

records = id (int, auto increment), name (varchar 250), age (int), address (varchar 250)
backup = id (int), name (varchar 250), age (int), address (varchar 250)

两个表内容3条记录。现在,我想按行的每列比较每行的这两个表,如果有一行与比较表上的相应行不匹配则生成并出错。

表“记录”内容:

row 1 : column id = 1, column name = name1, column age = 12, column address = USA
row 2 : column id = 2, column name = name2, column age = 17, column address = USA
row 3 : column id = 3, column name = name3, column age = 32, column address = USA

表“备份”内容:

row 1 : column id = 1, column name = name1change, column age = 12, column address = USA
row 2 : column id = 2, column name = name2, column age = 17, column address = USA
row 3 : column id = 3, column name = name3, column age = 32, column address = USA
从上面的表格内容可以看出,在表“备份行1,列名”中有一个更改,name1(记录表)更改为name1change(备份表)。因此,当表记录的第1行与表备份的第1行进行比较并找到差异时,它将获得行号和列名,后跟错误文本(参见下文)

echo $errorRow . "with" . $errorColumnOfTheErrorRow . "didn't match, there's is changes";

我希望循环到具有相同过程的记录结束(比较)。怎么做?任何想法,帮助,建议和建议将不胜感激。谢谢!

到目前为止,我尝试的是(参见下文)

$sql = "SELECT DISTINCT * FROM (SELECT a.* FROM records a UNION SELECT b.* FROM backup b ) c";
$result = mysqli_query($this->db,$sql);
$sql = "SELECT COUNT(*), id FROM (SELECT DISTINCT * FROM (SELECT a.* FROM records a UNION SELECT b.* FROM backup b ) c ) d GROUP BY id;";
$result = mysqli_query($this->db,$sql);

echo $result;

如上面的查询,我试图显示不匹配的行,但遗憾的是,没有工作。

1 个答案:

答案 0 :(得分:0)

你可以用一种很好的方式做到这一点: 第一步:将所有数据放在一起并仅保留不同的(=不相同的)行:

SELECT DISTINCT *
FROM (
SELECT a.*
FROM records a
UNION
SELECT b.*
FROM backup b ) c

第二步: 计算ID出现次数超过1次的所有记录:

SELECT COUNT(*), id 
FROM (
SELECT DISTINCT *
FROM (
SELECT a.*
FROM records a
UNION
SELECT b.*
FROM backup b ) c ) d
GROUP BY id
HAVING COUNT(*)>1;

这将为您提供行不相同的确切ID。

第三步: 获取包含更改数据的行:

SELECT * FROM (
SELECT "current data" AS description,f.* FROM 
records f
INNER JOIN (
SELECT id 
    FROM (
    SELECT DISTINCT *
    FROM (
    SELECT a.*
    FROM records a
    UNION
    SELECT b.*
    FROM backup b ) c ) d
    GROUP BY id
    HAVING COUNT(*)>1 ) e ON f.id=e.id
UNION 
SELECT "backup data" AS description, g.* FROM 
records g
INNER JOIN (
SELECT id 
    FROM (
    SELECT DISTINCT *
    FROM (
    SELECT a.*
    FROM records a
    UNION
    SELECT b.*
    FROM backup b ) c ) d
    GROUP BY id
    HAVING COUNT(*)>1 ) h ON g.id=h.id;
) i ORDER BY id ASC, description ASC;

它不漂亮,但它有效:)