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;
Run Code Online (Sandbox Code Playgroud)
fan*_*nts 12
你的陈述很好.唯一的问题是,你不能像普通的查询一样使用它.控制结构类似于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 $$
Run Code Online (Sandbox Code Playgroud)
并称之为:
call select_or_insert();
Run Code Online (Sandbox Code Playgroud)
而已.
| 归档时间: |
|
| 查看次数: |
34143 次 |
| 最近记录: |