简体   繁体   中英

INSERT INTO UPDATE with multiple unique column in mysql

I have a table with (id, stock_code, batch_code, qty) .

id is primary key and auto increment value.

stock_code and batch_code is combine unique. Now I want update in insert query when stock_code and batch_code is duplicate

example

id     stock_code     batch_code      qty
1      r001           b001            100
2      roo1           b002            100    //it should be insert
3      roo1           boo1            120    //it should be update in first row
4      roo2           boo1            130    //it should be insert
5      roo1           boo2            289    //it should be update in second row
$stockcode = "some value";
$batchcode="some value";
$qty = some value;
$con=mysqli_connect("localhost","my_user","my_password","my_db");

$query22 = "select * from table where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";

$result22 = mysqli_query($con,$query22) or die (mysqli_error());

$num22 = mysqli_num_rows($con,$result22);

if($num22 > 0) {
$query222 = "update table set qty='".$qty."' where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";

$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));  
 }
else {
$query222 = "insert into table(stock_code, batch_code, qty) values('".$stockcode."','".$batchcode."','".$qty."') ";

$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}

Try use

ON DUPLICATE KEY UPDATE

You can read the reff here http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

您正在寻找INSERT ON DUPLICATE KEY UPDATEhttp://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

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