简体   繁体   English

MySQL — 如果存在则更新,否则使用两个键插入

[英]MySQL — Update if exists else insert with two keys

I have a table with fields foreign_key_id |我有一个包含字段 foreign_key_id | 的表value1 |值1 | value2, and I want to update value2 if I have a match for foreign_key_id and value1. value2,如果我匹配 foreign_key_id 和 value1,我想更新 value2。

If foreign_key_id or value1 do not exist, I want to insert a new row.如果 foreign_key_id 或 value1 不存在,我想插入一个新行。 Is there a better way to do this than having PHP use a select statement and then branching to either an update or insert?有没有比让 PHP 使用 select 语句然后分支到更新或插入更好的方法?

Edit: value2 can be the same value as in the database, so I cannot run and update, see if affected_rows is 0, and run and insert if it is.编辑: value2 可以与数据库中的值相同,所以我无法运行和更新,查看affected_rows 是否为0,如果是则运行并插入。

Try using an IF EXISTS to determine whether to execute an UPDATE or an INSERT statement.尝试使用IF EXISTS来确定是执行UPDATE还是INSERT语句。 You can do this in one PHP statement/query.您可以在一个 PHP 语句/查询中执行此操作。

IF EXISTS(SELECT 1 FROM Mytable WHERE foreign_key_id = f1 AND value1 = v1)
BEGIN
    UPDATE Mytable SET value2 = v2
    WHERE foreign_key_id = f1 AND value1 = v1;
END
ELSE
BEGIN
      INSERT INTO Mytable(foreign_key_id,value1,value2)
      VALUES (f1,v1,v2);
END IF;

Yes, you can just run the update, then get the number of affected rows .是的,您可以只运行更新,然后获取受影响的行数 If this is 0, run the insert.如果为 0,则运行插入。 That will save you a select, because it is included in the update.这将为您节省 select,因为它包含在更新中。

[edit] [编辑]

Query as posted in the comments.查询如评论中发布。 Insert using select.使用 select 插入。 This will save an select upfront.这将预先节省 select。 You can use mysql_affected_rows to get the number of rows inserted.您可以使用 mysql_affected_rows 来获取插入的行数。 If it returns 0, you can update.如果返回 0,则可以更新。 It actually contains the select, so I'm not sure if it is fasters (mysql and subselects aren't exactly friends).它实际上包含 select,所以我不确定它是否更快(mysql 和子选择不完全是朋友)。 It will save you a roundtrip to the database however, and that might just make up for that.但是,它将为您节省往返数据库的时间,而这可能会弥补这一点。

insert into yourtable(f1, f2, fr) 
select 'value1', 'value2', 'value3' 
from dual /* yeah, I'm an Oracle dude */
where 
  not exists (
      select 'x' 
      from yourtable 
      where f1 = 'value1' and f2 = 'value2')

Try this slight modification if you cannot get p.campbell's solution to work如果您无法使 p.campbell 的解决方案发挥作用,请尝试此轻微修改

IF EXISTS(SELECT 1 FROM Mytable WHERE foreign_key_id = f1 AND value1 = v1) THEN
    UPDATE Mytable SET value2 = v2
    WHERE foreign_key_id = f1 AND value1 = v1;
ELSE
    INSERT INTO Mytable(foreign_key_id,value1,value2)
    VALUES (f1,v1,v2);
END IF;

Best option: Use REPLACE instead of INSERT or UPDATE .最佳选择:使用REPLACE而不是INSERTUPDATE It depends on the use of a primary key or unique key.这取决于使用主键或唯一键。

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

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