更新一个表,其中记录在另一个表中找到

时间:2013-04-16 09:21:29

标签: php mysql

我真的很想如何实现这一点,并希望有人能帮助我。我有现有的功能和查询:

public function setStockAndPrice($product_id) {
  $query = $this->db->query('UPDATE ' . DB_PREFIX . 'product SET quantity = 0, price = 0.00 WHERE product_id = ' . (int)$product_id)
}

这样可行,但是当我确实希望它只在另一个表中存在该产品时将产品设置为零时,它会将所有产品设置为零。

,即解释性词语:

public function setStockAndPrice($product_id) {
  $query = $this->db->query('UPDATE ' . DB_PREFIX . 'product SET quantity = 0, price = 0.00 WHERE product_id = ' . (int)$product_id AND product_id exists in CustomerProducts)
}

我不喜欢加入,但我不确定我是否需要在这里使用连接,因为查询看起来比这更简单。

有人能指出我正确的方向吗?

3 个答案:

答案 0 :(得分:2)

  public function setStockAndPrice($product_id) {
  $query = $this->db->query('UPDATE ' . DB_PREFIX . 'product SET quantity = 0, price = 0.00 WHERE product_id = ' . (int)$product_id ." AND product_id =(select DISTINCT(product_id) from CustomerProducts where product_id= $product_id)" )
  }

这可能有效。

答案 1 :(得分:0)

使用此功能可以为您分配db.product并确保在字符串中编写查询然后执行。

你看到你通过删除评论来查询

public function setStockAndPrice($product_id) {
  $query_string = "UPDATE " . DB_PREFIX . ".product SET quantity = '0', price = '0.00' WHERE product_id = '$product_id'";

  // echo "Query : " . $query_string;

  $query = $this->db->query($query_string);
}

答案 2 :(得分:0)

public function setStockAndPrice($product_id) {
      $query = $this->db->query('UPDATE ' . DB_PREFIX . '.product p, ' . DB_PREFIX . '.CustomerProducts cp SET p.quantity = 0, p.price = 0.00 WHERE p.product_id = ' . (int)$product_id . ' AND p.product_id = cp.product_id');
    }
相关问题