mysql insert or update,MySQL的:如果值存在更新否则插入

I have some code that looks like this. There is also an autoincrement field in the table that I must retain (it is used in other tables). I would like to simplify and optimize this code.

$query ="SELECT * FROM models WHERE col1 = 'foo'";

$testResult = mysql_query($query) or die('Error, query failed');

if(mysql_fetch_array($testResult) == NULL){

//insert...

$query ="INSERT INTO models (col1, col2, col3)

VALUES ('foo', 'bar', 'alph')";

$result = mysql_query($query) or die('Error, query failed');

}else{

//update...

$query = "UPDATE models

SET col1='foo', col2='bar', col3='alph'

WHERE col1='foo' AND col2='bar'";

$result = mysql_query($query) or die('Error, query failed');

}

Edit: The primary key id is the field that is auto incremented. I never want to alter this. However , when another field(s) is/are duplicated, this is when I want to update that record.

解决方案

How about REPLACE INTO:

REPLACE INTO models

( col1, col2, col3 )

VALUES

( 'foo', 'bar', 'alpha' )

Assuming col1 is your primary key, if a row with the value 'foo' already exists, it will update the other two columns. Otherwise it will insert a new row.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值