MySQL:在事务中,我可以在 IF 语句中使用 SELECT 的结果吗?

标签 mysql if-statement select transactions

我想检查数据库中是否已存在位置条目,因此在事务中我使用选择。

从城市=“伦敦”且国家/地区代码=“GB”的位置选择@location_id := location_id;

但在此之后,如果 @location_id 不返回任何内容,我希望创建位置,否则我将使用现有的 @location_id。我想这样的事情可能会起作用。

delimiter $$
if @location_id is null then
    select @location_id := max(location_id) from location;
    set @location_id = @location_id + 1;
    insert into location (location_id, city, country_code)
    values(@location_id, "London", "GB");
end if; $$
delimiter ;

(澄清一下:location_id 是位置表中的自动递增整数值)

“if 语句”的这种用法可以在事务中工作,或者在采用 @location_id 或过程的函数中工作吗?

最佳答案

经过进一步调查,我意识到我必须使用过程,因为您无法在函数内进行选择。最后我的解决方案是:

    delimiter $$
    CREATE PROCEDURE location_processor(in _city varchar(20),
    in _country_code varchar(2), out id int)
    begin
    select location_id into id from calendar.location
    where city = _city and country_code = _country_code limit 0,1;
    if id is null then
       select @id := max(location_id) from calendar.location;
       if @id is null then
          set @id = 0;
       end if;
       set @id = @id + 1;
       insert into calendar.location (location_id, city, country_code)
       values(@id, _city, _country_code);
       set id = @id;
    end if;
    end; $$
    delimiter ;

我使用以下方式调用它:

call calendar.location_processor("London", "GB", @id);
select @id;

关于MySQL:在事务中,我可以在 IF 语句中使用 SELECT 的结果吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43431526/

相关文章:

MySQL - 使用子查询更新

R,将 dplyr::mutate 与包含 grepl() 的 ifelse 一起使用会产生意外结果

Javascript 克隆节点未将所有值从克隆对象复制到新对象

php - MySQL "ERROR 1046 (3D000): No database selected"更新查询

MYSQL 如何匹配一个句子中的两个单词

c++ - 我的 if 语句打印在我的 while 循环中的每个 if 语句上,不管它是否为 false

string - 将单元格内容与 Excel 中的字符串进行比较

javascript - 在选择标签中更改时获取所选值

mysql - 内联注释如何绕过 SQL 注入(inject) Web 应用程序防火墙?

sql - 选择性导出MySQL数据库