选择是否存在其他插入?

时间:2013-08-17 07:58:42

标签: mysql

IF EXISTS (select * from users where username = 'something') THEN
    select id from users where username = 'something';
ELSE 
    insert into users (username) values ('something');
END IF;

3 个答案:

答案 0 :(得分:11)

你的陈述很好。唯一的问题是,你不能像普通的查询一样使用它。像IFWHILE这样的控制结构只能在存储过程或函数中使用。

只需创建一个这样的程序:

delimiter $$

create procedure select_or_insert()
begin

IF EXISTS (select * from users where username = 'something') THEN
    select id from users where username = 'something';
ELSE 
    insert into users (username) values ('something');
END IF;

end $$

并将其称为:

call select_or_insert();

就是这样。

答案 1 :(得分:1)

您可以尝试这样: -

if exists( select * from mytable where field = 'something') 
begin
   select somefield from mytable where field = 'something';
end
else
 begin
    insert into users (username) values ('something');
end

if not exists( select * from mytable where field = 'something') 
begin
    insert into users (username) values ('something');       
end
else
 begin
    select somefield from mytable where field = 'something';
 end

虽然上述两个查询都相同。

或尝试使用if:

IF EXISTS (select * from mytable where users = 'something')
    select field from mytable where users = 'something'
else
    into mytable (users) values ('something')

以下是SQLFIDDLEDEMO

答案 2 :(得分:0)

以接受的答案为基础,但只需要一次SELECT调用(为MySQL编写):

delimiter $$

create procedure select_or_insert()
begin

SET @myId := (SELECT id FROM users WHERE username = 'something');

IF (ISNULL(@myId))
    THEN 
        INSERT INTO users (username) VALUES ('something');                 
END IF;

end $$

如果需要,可以使用LAST_INSERT_ID()函数有效地选择新插入的元素:

SELECT @myId := LAST_INSERT_ID();