[英]INSERT INTO UPDATE with multiple unique column in mysql
I have a table with (id, stock_code, batch_code, qty)
. 我有一个
(id, stock_code, batch_code, qty)
。
id
is primary key and auto increment value. id
是主键和自动递增值。
stock_code
and batch_code
is combine unique. stock_code
和batch_code
是唯一的组合。 Now I want update in insert query when stock_code
and batch_code
is duplicate 现在,当
stock_code
和batch_code
重复时,我想在插入查询中更新
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 您可以在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.