MYSQL:存储过程,插入一行,然后通过 LAST_INSERT_ID() 选择它

标签 mysql stored-procedures last-insert-id

我正在尝试创建一个存储过程调用 AddCluster 女巫正在接受参数“title”和“alt”

案例 1:

如果 'title' 在数据库中,则只返回“旧”行!

案例 2:

如果“标题”不在数据库中,则

根据 parmerer 'title' 和 'alt' 插入一行

然后通过LAST_INSERT_ID()选择新添加的行

问题出在情况 2 上,它只返回空!!

-- --------------------------------------------------------------------------------
-- AddCluster Group Routines
-- --------------------------------------------------------------------------------
DELIMITER $$

CREATE DEFINER=`linkbay_dk`@`%` PROCEDURE `AddCluster`(in in_title varchar(45), in in_alt text)
BEGIN
    /* check if 'in_title' is in db */
    IF EXISTS
    (
        SELECT count(*) FROM Cluster 
        WHERE title=in_title 
    )
    THEN
        /* returns old Cluster there is in db */
        SELECT * FROM Cluster WHERE title=in_title; 
    ELSE
        INSERT INTO Cluster
        (
            `id`,
            `create_at`,
            `title`,
            `alt`
        )
        VALUES
        (
            null,
            NOW(),
            in_title,
            in_alt
        );
        /* returns the newly added Cluster */
        SELECT * FROM Cluster WHERE id=LAST_INSERT_ID();
    END IF;
END$$

最佳答案

尝试在不指定 id 的情况下插入:

...
ELSE
    INSERT INTO Cluster
    (
        `create_at`,
        `title`,
        `alt`
    )
    VALUES
    (
        NOW(),
        in_title,
        in_alt
    );
    /* returns the newly added Cluster */
    ...

确保 Cluster.id 是一个 AUTO_INCREMENT 列,只有这样您才能使用 LAST_INSERT_ID() 获取值。

关于MYSQL:存储过程,插入一行,然后通过 LAST_INSERT_ID() 选择它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10676268/

相关文章:

mysql - MySQL Select 查询执行缓慢

java - 读取输出参数后无法获取结果集

mysql - 在事件中运行某些程序失败

PHP Postgres : Get Last Insert ID

mysql - Hibernate允许外键成为众多类之一吗?

MySQL - 根据该列乘以值

mysql - 返回与 mySQL 中的存储过程中的第一个字符匹配的结果

mysql - AUTO_INCREMENT 在我的案例中是否正确实现?

mysql - 如何检索最后添加的项目的实例

mysql - SQL 分组依据和排序依据问题