您的位置 首页 php

PHP MySQL 新旧两张数据表找不同数据并在新表数据输出中标记

场景:原有一张数据表[old],在经过几个月的增删改后形成了新的数据表[new],数据结构不变化。现在需要在输出new这张表时,需要与old数据表对比,找出相同主键下改变的字段及新增的记录,并用特殊符号标记出来,方便后续处理。

示例:clxh字段是主键, timestamp是保存时的时间戳,C1到C5是可能变化的字段

old数据表

new数据表

变化的可能性分析:

1)数据被删除,如HFC2何HFC3;

2)新增数据,如HFC8何HFC9;

3)部分字段的数据被修改,如HFC和HFC6;

 <?php
// set_time_limit(0);//取消PHP30秒限制
require_once('../basic/Mysql.php');

function strsplit($str){//将含有'|'的字符串按'|'分割
    //如分隔后两个值不同则取第一个值并注上标记【$】,分隔后两个值相同在仅取第一个值;
    if (strstr($str,'|')) {//如果有|
        $arr=explode('|',$str);
        if ($arr[0]==$arr[1]) {
            return $arr[0];
        } else {
            return '$'.$arr[0];
        }        
    }else{
        return $str;
    }
}

$newtable="new";
$oldtable="old";
$c=new Mysql();
//1、合并2张表(去重),将数据放入新的表中
$sql="drop table zh_ls if exists";
$c->dropTable($sql);
$sql="create table zh_ls SELECT * FROM ".$newtable." UNION SELECT * FROM  ".$oldtable;
$c->creatTable($sql);
//  2、查找新表被删除的车型
$sql="drop table zh_ls_del if exists";
$c->dropTable($sql);
$sql="create table zh_ls_del SELECT  clxh  ".$oldtable."  where clxh not in(SELECT clxh FROM ".$newtable.")";
$c->creatTable($sql);
// 3、从zh_ls删除被删除的数据
$sql="delete from zh_ls where clxh in(select clxh from zh_ls_del)";
$c->deleteTable($sql);
// 4、查找新表新增的车型
$sql="drop table zh_ls_add if exists";
$c->dropTable($sql);
$sql="create table zh_ls_add SELECT  clxh FROM ".$newtable."  where clxh not in(SELECT clxh FROM ".$oldtable.")";
$c->creatTable($sql);
// 5、更新zh_ls中新增车型的车辆型号字段,在字段clxh上并上@特殊字符
$sql="update zh_ls set clxh= concat('@',clxh) where clxh in (select clxh from zh_ls_add)";
$c->updateTable($sql);
// 6、为找多条记录变化字段,将多条记录按车辆型号分组合并成1条。
//合并时按timestamp降序排列,保证最新数据放在最前面,“|”符号分隔
//同时定义一个strsplit($str)函数来拆分并标记变化的字段
$sql="SELECT clxh,group_concat(c1 order by timestamp  desc separator '|')as c1,group_concat(c2 order by timestamp  desc separator '|')as c2,group_concat(c3 order by timestamp  desc separator '|')as c3,group_concat(c4 order by timestamp  desc separator '|')as c4,group_concat(c5 order by timestamp  desc separator '|')as c5,group_concat(timestamp order by timestamp  desc separator '|')as timestamp  FROM `zh_ls`   group by clxh";
$re=$c->selectTable($sql);
$arr=$c->jdecode($re);
$total= $arr['total'];
$data= $arr['data'];
if ($total>0) {
    for ($i=0; $i <$total ; $i++) {  
        foreach($data[$i] as $k=>$v){
            $data[$i][$k] =strsplit($v);//标记变化字段的值
        }       
    }  
}
return $data;
//7、此时返回的数据中就将新表已删除的数据删除,新增加的数据在clxh前加@,变化的字段前加#字符了。
  

返回数据

感觉我这个过程比较麻烦,你们是如何解决这个问题的,有什么好的思路?

文章来源:智云一二三科技

文章标题:PHP MySQL 新旧两张数据表找不同数据并在新表数据输出中标记

文章地址:https://www.zhihuclub.com/77734.shtml

关于作者: 智云科技

热门文章

网站地图