• mysql整合有关联的两个数据表里的字段



    在整合两个数据表时,要把B表的一个字段整合到A表中来,B表有A表的主键的外键。
    有两种方法(目标表TableA,来源表TableB):
    1、通过程序(通过php实现),分两步实现

    a.查询目标表里所有的id号,放到一个数组里$arrid
    b.遍历$arrid,根据id号,从备份表里取出对应id的记录,取目标字段值$column,赋值给目标表的对应字段

    ps:若数据量太大,有可能会出现运行超时,这是也可以通过更改php的最大执行时间才解决。

    php文件:copdb.php

     1 <?php
     2 require "conntodb.php";
     3 
     4 function copdb($sql){
     5     $result = mysql_query($sql);
     6     if ($result) {
     7         return $result;
     8     }else{
     9         return "error";
    10     }
    11 }
    12 ?>

    php文件:dbModel.php

     1 <?php
     2 require "copdb.php";
     3 
     4 function select(){
     5     $sql = "select * from TableA";
     6      $result = copdb($sql);
     7     return $result;
     8 }
     9 
    10 function update($id){
    11     $result = find($id);
    12     $field1 = "null";
    13     while ($row = mysql_fetch_array($result)) {
    14          $field1 = $row['field1'];
    15     }
    16     $sql = "update TableA set field1 ='".$field1 ."'  where id='".$id."'";
    17     $result = copdb($sql);
    18 }
    19 
    20 function find($id){
    21     $sql = "select * from TableB where ta_id=".$id;
    22     $result = copdb($sql);
    23     return $result;
    24 }
    25 ?>

    php文件:select.php

     1 <?php
     2 /*
     3 查询主表里所有的id号,放到一个数组里$arrid
     4 遍历$arrid,根据id号,从副表里取出对应的字段值$column
     5             根据id号,把$column插入到主表对应的列里
     6 ----------------------------------------------------
     7 
     8 */
     9 require "dbModel.php";
    10 //查询目标表里的所有id号
    11 function selectallid(){
    12 $result = select();
    13 $arr = array();
    14 while ($row = mysql_fetch_array($result)) {
    15     $arr[] = $row["id"];
    16 }
    17 return $arr;
    18 }
    19 
    20 
    21 
    22 //遍历id数组,执行更新操作
    23 function bianliid(){
    24     $arr = selectallid();
    25     for ($i=0; $i < count($arr); $i++) { 
    26         update($arr[$i]);
    27     }
    28 }
    29 bianliid();
    30 
    31 ?>

    2、通过sql语句:
    UPDATE TableA AS ta,TableB AS tb SET ta.field1 = tb.field1 WHERE ta.id = tb.ta_id





  • 相关阅读:
    asp网站如何制做动态实时sitemap?
    java线程 Thread
    java set集合
    java 集合
    java IO复制文件
    java 通过map统计输入字符的个数
    java的反射
    java 多线程买票案例
    java泛型
    java对象的反序列化和序列化
  • 原文地址:https://www.cnblogs.com/TimeStory/p/4168493.html
Copyright © 2020-2023  润新知