php - 有条件插入 MySQL - WHERE NOT EXISTS

标签 php mysql sql-insert

当客户还没有购买产品的记录时,我尝试执行 INSERT INTO 查询。

我尝试了下面的SQL,但它似乎不起作用。

$queryAddPurchase = "INSERT INTO purchase (UserID, Product, Price) 
              VALUES ('$userID', '$product', '$price')
              WHERE NOT EXISTS(SELECT Product
                                       FROM purchase
                       WHERE Product = '$product'
                       AND UserID = '$userID')";

我收到的错误如下:

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 Product FROM purchase ' at line 3

如有任何建议,我们将不胜感激!

最佳答案

假设用户只能购买每种产品中的一种(永远且适用于所有产品)。

ALTER TABLE purchase ADD UNIQUE KEY (`UserID`, `Product`); -- run this just once. this changes the table

INSERT IGNORE INTO purchase (UserID, Product, Price) VALUES ('$userID', '$product', '$price');

请注意,这会阻止他多次购买任何产品,这可能不是理想的结果。

关于php - 有条件插入 MySQL - WHERE NOT EXISTS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15647629/

相关文章:

python - 插入数据而不是删除表到mysql

php - FOS Elastica嵌套过滤器不起作用

php - 正则表达式 mysql 函数

javascript - 如何将 PHP 用户详细信息( session )解析到 Node.js 服务器?

MySQL触发器: #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version

c# - 插入 SQL 数据库,在带有复选框列表的 foreach 中

通过选择不同值插入查询中的 MySQL 语法错误

php - 我需要哪个选项来使用 HHVM 编译 php 代码

sql - 将 MYSQL 查询的 1 列设置为 Null

php mysql下拉问题