如果存在则更新,如果不存在则插入 [英] Update if exist, insert if not exist

查看:331
本文介绍了如果存在则更新,如果不存在则插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
如何操作我是否更新(如果存在),如果不存在,则插入MySQL(又称为upsert或merge)?

Possible Duplicate:
How do I update if exists, insert if not (aka upsert or merge) in MySQL?

我有可以为预订引擎批量更新价格的程序.

I have program that can do batch updating price for booking engine.

用于更新批量价格的示例用户输入是这样的

example user input for to do update batch the price is like this

$dateStart = '2012-12-01';
$dataEnd = '2012-12-31';
$hotelId = 1;
$price = 300000;

数据库就是这样

id | date       | hotelId | price
1  | 2012-12-01 | 1       | 100000

如果datehotelId已经存在,MySQL查询应该如何进行批处理更新并在有条件的情况下进行插入,然后进行更新,但是如果不存在,则进行插入?

How should the MySQL Query, to do batch update and insert with condition if date and hotelId is already exist then do update, but if not exist do insert?

我知道如果每天进行循环并检查PHP中的数据是否存在,确实会占用大量内存.

I understand if doing looping day by day and checking if data exist or not in PHP will be really spend much memory.

for($i=1; $i<=31; $i++){...}

我正在寻找解决方案,如何使用单个/任何可以节省计算机资源的mysql查询来完成.

I'm looking solution how it can be done with single/any mysql query that can save computer resource.

推荐答案

使用 INSERT ... ON DUPLICATE KEY UPDATE ... 语句.

这将要求您在datehotelId列上具有UNIQUE或PRIMARY复合索引,以便触发DUPLICATE KEY条件.

It will require that you have a UNIQUE or PRIMARY compound index on the date and hotelId columns so that the DUPLICATE KEY condition is triggered.

这篇关于如果存在则更新,如果不存在则插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆