如果id尚不存在,则SQL仅向MYSQL表中插入新行

时间:2014-05-22 10:26:55

标签: php mysql sql

我有一个名为sales的mysql数据库表,其列为id | timeStamp | timeString |如果表中尚不存在ID,我想要插入新值的EAN。例如,我可能想添加:

 9997a04fe3f932bf6f8e9d88f4b8dc96 | 0000003082461 | 11:07 (Thu. 22 May. 2014 | 1400716800

到数据库表中,如果id为	 9997a04fe3f932bf6f8e9d88f4b8dc96'之前还没有输入过。

到目前为止我写的SQL看起来像这样:(使用1234作为虚拟值,表中已经有一行,id为1)

 INSERT INTO `sales`(`id`, `timeStamp`, `timeString`, `EAN`) VALUES (1,2,3,4)
    WHERE NOT EXISTS (
        SELECT `id` FROM `sales` WHERE `id` = '1'
    )

请帮我搞定这个SQL语句。目前报告语法错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE NOT EXISTS ( SELECT `id` FROM `sales` WHERE `id` = 1 ' at line 2

2 个答案:

答案 0 :(得分:4)

向ID列添加唯一索引,然后使用INSERT IGNORE语句

答案 1 :(得分:0)

在INSERT语句之前,您需要检查数据是否存在。如果退出只是给已存在的用户数据或任何你想要的信息。

喜欢这个

     $result = mysqli_query ($con,"SELECT COUNT(id) FROM sales WHERE (id='$id')");
     $row = mysqli_fetch_row($result);
     $total_records = $row[0];
     if($total_records == 0)

     {
       INSERT INTO sales(`id`, `timeStamp`, `timeString`, `EAN`) VALUES        
       ($id,$timestamp,$timestring,$Ean);   

      } else
      { 
             --------------Enter-----
            ------------Error message------
      }