0

我想编写一个函数来检查数据库中是否存在对象 - 返回它的 id 或者如果不存在 - 创建对象并返回它的 id。

所以我创建了这个代码:

drop function if exists getAuthorId;

DELIMITER  //

CREATE FUNCTION getAuthorId(anonym varchar(255) CHARACTER SET utf8, ispublic tinyint(1))     RETURNS INT
   BEGIN
   DECLARE y INT;
   IF (SELECT id INTO y FROM library_author where library_author.slug = getSlug(anonym) limit 1) THEN

    **# Here is need to make second select, cause if I just return y - it will be empty 
    Why ??**

       SELECT id INTO y FROM library_author where library_author.slug = getSlug(anonym) limit 1;
   RETURN y;
ELSE
    INSERT INTO author set author.anonym = anonym, author.slug = getSlug(anonym), author.is_public = ispublic, author.date_created = CURDATE();
    RETURN last_insert_id();
END IF;
END // 

DELIMITER ;

有什么方法只使用一个选择请求吗?

4

1 回答 1

0

尝试这个:

DECLARE y INT;  
SELECT id INTO y FROM library_author where library_author.slug = getSlug(anonym) limit 1;  
IF( !ISNULL( Y )) then return Y;
   else return 0;  
end if;
于 2012-12-10T13:35:23.133 回答