简体   繁体   中英

how to update a table and insert a new record to another table in one query?

I have two table in mysql that is product and sell. The product contain the stock and the sell contain the purchasing record. Now i want to sell a product from the stock when i insert the quantity of selling item into the sell table then the same amount should be decrease in the stock that is product table. Please help me for the query.

Sell table insertion.

    $cus_id = $_POST['customer'];
$reg_id = $_POST['cus_region'];
$cat_id = $_POST['product'];
$name = $_POST['name'];
$price = $_POST['unit_price'];
$quantity = $_POST['quantity'];
$date = $_POST['datepicker'];
$total = $price * $quantity;
$payment = $_POST['payment'];
$remainig = $total - $payment;

$query = "INSERT INTO sell SET cus_id = '".$cus_id."',reg_id = '".$reg_id."', cat_id = '".$cat_id."',product = '".$name."',selling_price = '".$price."',selling_date = '".$date."',item_quantity = '".$quantity."',amount_paid= '".$payment."',total_price = '".$total."', remaining = '".$remainig."'";

$res = mysql_query($query);

Two way to resolve that,

1) if you are getting the quantity of product you can make second query to deduct the quantity from stack table (product table)

2) You can use trigger for such operations, while you insert in to sales table that same quantity you can reduce from the product table

You have to just change or decrease the quantity of the product in PRODUCT table. So, you have to use UPDATE query.

This can solve your issue: 1) I consider that your cat_id is the unique product key to identify a product in your PRODUCT table.

2) I consider that you have quantity column in PRODUCT table, which store the quatity of the product. And 1 product is being sold at a time.

UPDATE TABLE_NAME SET quantity = quantity - 1 WHERE cat_id = "SOME_INT_ID_WITHOUT_QUOTES"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM