简体   繁体   English

MySQL过程 - 如果不存在则插入行

[英]MySQL Procedure - Insert row if not exists

OK, this is what I want to do : 好的,这就是我想要做的:

  • If an entry already exists (eg based on field name ), then just return its id 如果条目已存在(例如,基于字段name ),则只返回其id
  • If it doesn't, add it 如果没有,请添加它

This is what I've managed so far (for the "if doesn't exist, create it" part) : 这是我到目前为止所管理的(对于“if not exists,create it”部分):

INSERT INTO `objects` (`id`,`name`)
    SELECT NULL,'someObj2' FROM `objects`
        WHERE NOT EXISTS
             (SELECT name FROM `objects` WHERE `name`='someObj2');
SELECT LAST_INSERT_ID();

How can I get the id (instead of LAST_INSERT_ID() ) if the entry does exist? 如果条目确实存在,我如何获取id (而不是LAST_INSERT_ID() )?


PS Yep, I know that the main reason I can't get my head around SQL is the degree at which I'm used to the more classical if-then-else approach of regular programming languages... lol PS是的,我知道我无法理解SQL的主要原因是我已经习惯了常规编程语言的更经典的if-then-else方法... lol


UPDATE : 更新:

I keep trying and trying and this what I've managed so far (as a stored procedure) : 我一直在尝试和尝试这个我到目前为止所管理的(作为存储过程):

IF EXISTS (SELECT * FROM `objects` WHERE `name` = NAME) 
THEN
    SELECT `id` FROM `objects` WHERE `name` = NAME;
ELSE
    INSERT INTO `objects` (`id`,`name`) VALUES(NULL,NAME);
    SELECT LAST_INSERT_ID() AS 'id';
END IF

and calling it like: CALL insertObject("someObj2"); 并调用它: CALL insertObject("someObj2");

However, it's not working as expected - neither does it add the entry, nor does it return the id (instead it returns all id s in the table...). 但是,它没有按预期工作 - 它既没有添加条目,也没有返回id(而是返回表中的所有 id ...)。 Any idea what could be going wrong? 什么可能出错?

It looks like you are trying to enforce a unique constraint on name . 看起来您正在尝试对name强制执行unique约束。 If so, you can also do this by just declaring the column to be unique or equivalently creating a unique index: 如果是这样,您也可以通过将列声明为unique或等效创建唯一索引来执行此操作:

create unique index objects_name on objects(name);

If this is true, then change the question from getting the last inserted id to just getting the id for name : 如果这是真的,那么将问题从获取最后插入的id更改为仅获取nameid

select id
from objects o
where o.name = 'someObj2';

I hasten to add that in a high-transaction environment where things are being added and deleted quickly, any approach might have a problem. 我赶紧补充一点,在高事务环境中快速添加和删除内容,任何方法都可能有问题。 Consider your code, the row could be inserted and then deleted, even before the last_insert_id() is executed. 考虑一下你的代码,即使在执行last_insert_id()之前,也可以插入然后删除该行。 If you are dealing with a high transaction environment with potential race conditions, then you need to use transactions and locking to do what you want. 如果您正在处理具有潜在竞争条件的高事务环境,那么您需要使用事务和锁定来执行您想要的操作。

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

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