简体   繁体   English

MYSQL更新(如果存在或插入)

[英]MYSQL update if exists or insert

I have been trying to get the following SQL to work however it seems to skip the insert function. 我一直在尝试使以下SQL工作,但是似乎跳过了插入功能。 Essentially updating should take priority as most of the time it should fire. 从本质上讲,更新应该在大多数时候被优先处理。

UPDATE `teams-tasks`
        SET status=(:s), name=(:n), description=(:d), importance=(:i), applies=(:a) 
        WHERE teamId =(:t) AND date=(:da) AND playerId =(:p) AND creatorId =(:c);
        IF (SELECT ROW_COUNT() = 0);                    
        INSERT INTO `teams-tasks`
            ( status, date, creatorId, teamId, playerId, name, description, importance, applies ) 
        VALUES 
            ( (:s), (:da), (:c), (:t), (:p), (:n), (:d), (:i), (:a) ))

what am i doing wrong? 我究竟做错了什么? i am using php pdo for my database connection if it matters 如果有问题,我正在使用php pdo进行数据库连接

thanks 谢谢

User replace into query which makes sure if the row exists it will update the data, if row does not exists it will insert the date. 用户替换为查询,以确保该行是否存在将更新数据,如果该行不存在则将插入日期。

to check the duplicate entry it compares the primary key internally 检查重复的条目,它在内部比较主键

eg 例如

REPLACE INTO table_name(column_name1,column_name2,…)
VALUES(value1,value2,…)

eg 例如

REPLACE INTO offices(officecode,city)
VALUES(8,'San Jose')

Thanks Amit 谢谢阿米特

You should use INSERT ... ON DUPLICATE KEY UPDATE 您应该使用INSERT ... ON DUPLICATE KEY UPDATE

For example 例如

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM