简体   繁体   English

如果同一表的其他版本中不存在ID,则将行添加到表中

[英]Add row in to a table if ID does not exist in other version of the same table

I searched the solution in google but I can't find (or I don't understand) the right solution. 我在Google中搜索了解决方案,但找不到(或我不明白)正确的解决方案。 I have two tables, they are the same, but in the newest version, some rows have been loose. 我有两个表,它们是相同的,但是在最新版本中,有些行是松散的。 So I would like to be able to compare this two tables and inject the missed rows by comparing the ID. 因此,我希望能够比较这两个表并通过比较ID来注入丢失的行。 For example: If in the table v1 we have the row with the ID 12 and not in the table of the v2 then we add this row in the v2 table. 例如:如果在表v1中我们有ID为12的行,而不在v2表中,那么我们将此行添加到v2表中。

I wrote an php script but I can't go further, I don't get it how I can compare this values at the same time, maybe I'm using a bad approach, here is my php code: 我写了一个php脚本,但我走不远了,我不明白如何同时比较这些值,也许我使用的是错误的方法,这是我的php代码:

<?php
    function_db_connect();
    $req_src = "SELECT * FROM `table_v1` ";

    $req_ex_src=mysql_query($req_src) or die("Erreur: ".mysql_error());

    $i =0;

    while($row = mysql_fetch_array($req_ex_src)) {
        $i = $i +1;
        $rowID[$i] = $row['ID'];
    }

    mysqli_close();

    $n = count($rowID);

    for ($j=0;$j<=$n;$j++){
       ??????????????????????
    }

I get all the ID in an array and my idea was to compare this values with the v2 table in the for loop. 我得到了数组中的所有ID,我的想法是将此值与for循环中的v2表进行比较。

That's all I have done, I'm a little confused... Do you think there's another method better than this? 这就是我所做的一切,我有些困惑……您认为还有另一种方法比这更好吗?

You can use a simple mysql query to do this no need to use php unless there are other factors needing to be taken into account 您可以使用简单的mysql查询来执行此操作,除非需要考虑其他因素,否则无需使用php

To do this use insert ignore: 为此,请使用插入忽略:

INSERT IGNORE INTO table_v2 (SELECT * FROM table_v1)

this will select all the rows in table_v1, and try to insert them into table_v2, if a row's keys already exist that row is ignored and the query continues on. 这将选择table_v1中的所有行,并尝试将它们插入到table_v2中,如果某行的键已经存在,则该行将被忽略并且查询将继续进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM