当客户还没有购买产品的记录时,我尝试执行 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/