doushan5245 2017-01-28 23:47
浏览 31
已采纳

SQL Join语句使用PHP循环更新整个列

I need to update an entire column with new unique phone numbers that live in a second table. I seem to be on the right track... but my loop logic is faulty.

I'm returning the matches correctly as far as I can tell, but when I try to update the entire column in the table it inserts the last phone number in every single row.

$query = "SELECT matched.duns, matched.new_p1, users_data.temp_duns
          FROM matched 
          INNER JOIN users_data ON temp_duns
          WHERE temp_duns = duns LIMIT 10";
$result = mysqli_query($connection, $query);

foreach ($result as $key => $val) { 
        if($val['duns'] === $val['temp_duns']) {
            $final_query = "UPDATE users_data SET phone_number = " . $val['new_p1'];
            $final_result = mysqli_query($connection, $final_query);        
            echo $counter . "DUNS From matched: " . $val['duns'] . " DUNS From users_data: " . $val['temp_duns'] .  " NEW PHONE: ".  $val['new_p1']. "<br>";
        }       
    }

I'm a total newb but any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • douwen0612 2017-01-29 01:57
    关注

    Simply run an update query in one call without looping and in MySQL INNER JOIN can be used:

    UPDATE user_data u
    INNER JOIN matched m ON u.temp_duns = m.temp_duns
    SET u.phone_number = m.new_p1;
    

    Or for the limit of 10:

    UPDATE user_data u
    INNER JOIN (SELECT * FROM matched LIMIT 10) m ON u.temp_duns = m.temp_duns
    SET u.phone_number = m.new_p1;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化