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

时间:2017-04-15 21:37:47

标签: mysql if-statement select transactions

我想检查数据库中是否已存在Location条目,因此在事务中我使用select。

select @location_id := location_id from location where city = "London" and country_code = "GB";

但是在此之后我想要在@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是位置表中的auto_incremented整数值)

“if语句”的这种用法是否可以在事务中或者在使用@location_id或过程的函数内工作?

1 个答案:

答案 0 :(得分:0)

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

    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;