2

当客户还没有购买产品的记录时,我正在尝试进行 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')";

我收到的错误如下:

您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的“WHERE NOT EXISTS(SELECT Product FROM purchase”附近使用正确的语法

任何建议将不胜感激!

4

2 回答 2

1

On the assumption, that a user may only buy one of each product (ever and for all products).

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');

Be aware, that this then prevents him from buying any product multiple times, which might not be the desired outcome.

于 2013-03-26T21:23:32.083 回答
1

如果可能,向表中添加一个 UNIQUE 约束。就像是 ...

alter table purchase add unique user_product (UserID, ProductID);

你的条件插入变得微不足道:

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

如果这适合您,请在此处使用所选答案:MySQL Conditional Insert

简而言之,这个答案:

INSERT INTO purchase (UserID, Product, Price) 
    SELECT '$userID', '$product', '$price'
    FROM dual
        WHERE NOT EXISTS (
            SELECT * FROM purchase
            WHERE UserID='$userID'
                AND ProductID='$product'
        )
于 2013-03-26T21:24:18.853 回答