我有一个名为sales的mysql数据库表,列id | timeStamp | timeString | EAN,如果id不存在于表中,我想插入新的值。例如,我可能想添加:
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
为ID列添加唯一索引,然后使用INSERT IGNORE语句
在执行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------
}