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;
问问题
36597 次
3 回答
13
你的陈述很好。唯一的问题是,您不能像普通查询一样使用它。IF
类似或的控制结构WHILE
只允许在存储过程或函数中使用。
只需创建一个这样的过程:
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();
而已。
于 2013-08-17T11:07:31.027 回答
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')
于 2013-08-17T08:01:19.170 回答
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();
于 2018-05-04T18:54:26.610 回答