0

我有一个带有两个表的 mysql 数据库。第一个表称为“uniqueReferences”,第二个表称为“duplicatedReferences”。这两个表只有两个字段:一个 id 字段(自动递增)和一个名为 Reference 的字段。我想要的是如下。尝试在“uniqueReferences”表中插入引用时,如果引用已存在,请不要将其插入该表中,而是插入“duplicatedReferences”表中。

所以我尝试但没有奏效的是以下内容。
1-> 将我的“uniqueReferences”表的字段引用设置为“唯一”。
2->进行以下操作

try{  
         $req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));

         if($req == 0){
               $prepared_insertQry_toDuplicateRefTable->execute(array(something));
         }
     }
    catch(PDOException $e){echo $e->getMessage();}

不幸的是,这不起作用。我有以下错误SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry。希望有人可以提供帮助。干杯。马克

4

3 回答 3

1

根据您收到的消息,您似乎正在捕获 PDOException,其中的消息是... 1062 Duplicate entry. 这意味着您的“uniqueReferences”表上的表约束不允许重复条目。可能是因为您在该表中有一个主键。这是一件好事,它将使这个问题更容易解决。

因此,如果每次尝试插入重复条目时都抛出异常,那么我们就知道要插入到“duplicatedReferences”表中。您只想验证抛出的异常是由于重复条目造成的。

试试这个:

try
{
    $prepared_insertQry_toUniqueRefTable->execute(array(something));
}
catch (PDOException $e)
{
    if ($e->getCode() == 1062)
        $prepared_insertQry_toDuplicateRefTable->execute(array(something));
    else
        echo $e->getMessage();
}
于 2012-05-02T13:36:19.910 回答
1

请参阅我的注释与代码内联:

    try{  
         $req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));

         // this never executes because an Exception halts it here
         /*if($req == 0){
               $prepared_insertQry_toDuplicateRefTable->execute(array(something));
         }*/
     }
    catch(PDOException $e){
       // this catch grabs the exception and executes the code within instead
       // that code might log an error, echo the error message, or perform
       // alternative logic. In your case you want to execute alterntative logic
       // ie. your query
       $prepared_insertQry_toDuplicateRefTable->execute(array(something));

   }
于 2012-05-02T13:37:33.993 回答
1

尝试先插入数据,如果它已经存在,则将其插入表中以查找重复行。由于如果该行存在则生成异常,您可以捕获此异常,然后将该行插入到重复的表中:

try
{  
    $req = $prepared_insertQry_toUniqueRefTable -> execute(array(something));
}
catch (PDOException $e)
{
    // you can use the value of errorInfo[1] to check the actual generated error code
    if ($e->errorInfo[1] == 1062)
    {
        $prepared_insertQry_toDuplicateRefTable->execute(array(something));
    }
    else
    {
        // rethrow the exception as we're not handling it
        throw $e;
    }
}

你可能需要稍微调整一下才能得到你想要的,但这应该是它的要点。

于 2012-05-02T13:38:21.790 回答