如果存在则更新,如果不存在则插入
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
如果date
和hotelId
已经存在,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 ...
语句.
这将要求您在date
和hotelId
列上具有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.