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





转载于:https://www.cnblogs.com/TimeStory/p/4168493.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值