如何在select子查询和where子句中使用insert查询?

时间:2015-09-08 06:30:23

标签: php mysql

我正在使用它,但它出错了

$sql="INSERT INTO `shopping_cart`  
(userid`,`product_id`,`pr_name`, `pr_price`)  
VALUES('$us_id','$pr_id','$pname','$prprice')  
WHERE(SELECT `product_id` FROM `product_tb_men`  
JOIN `shopping_cart` ON product_tb_men.pr_id= shopping_cart.product_id  
WHERE product_tb_men.pr_id=$pr_id)";

3 个答案:

答案 0 :(得分:0)

可能你需要这个:

UPDATE `shopping_cart` 
SET userid = '$us_id',
  `product_id` = '$pr_id',
  `pr_name` = '$pname', 
  `pr_price` = '$prprice'
WHERE <field_name_for_id> IN (SELECT `product_id` FROM `product_tb_men`  
 JOIN `shopping_cart` ON product_tb_men.pr_id= shopping_cart.product_id  
 WHERE product_tb_men.pr_id='$pr_id')

答案 1 :(得分:0)

WHERE子句不能与INSERT一起使用。 SELECT我下面的子查询保留了你给出的内容。更改位于剩余的主要查询

UPDATE `shopping_cart` 
    SET `userid` = '$us_id', 
      `product_id` = '$pr_id', 
      `pr_name` = '$pname', 
      `pr_price` = '$prprice'
    WHERE `product_id` in (SELECT `product_id` FROM `product_tb_men`  
     JOIN `shopping_cart` ON product_tb_men.pr_id= shopping_cart.product_id  
     WHERE product_tb_men.pr_id=$pr_id);

答案 2 :(得分:0)

尝试此查询:

"INSERT INTO `shopping_cart` (`userid`,`product_id`,`pr_name`, `pr_price`)  
SELECT '$us_id', '$pr_id','$pname','$prprice' FROM `product_tb_men` 
JOIN `shopping_cart` ON product_tb_men.pr_id= shopping_cart.product_id  
WHERE product_tb_men.pr_id= $pr_id"