MySql: Insert a row and get the content

后端 未结 5 1285
轻奢々
轻奢々 2020-12-01 18:27

Is it possible to insert a row and get the values inserted in the same query?

Something like...

INSERT INTO `items` (`item`, `number`, `state`) 
(SEL         


        
相关标签:
5条回答
  • 2020-12-01 18:42

    if you are using php then

    instead of this you can use

    mysql_insert_id();
    

    which will give the id of last inserted record.

    The other data will be same as inserted. Only id will change which you can get by mysql_insert_id()

    So you do not need to run second query.

    0 讨论(0)
  • 2020-12-01 18:49

    you can call a stored procedure which will perform the insert and return a resultset in a single call from your app layer to mysql:

    Stored procedure call

    mysql> call insert_user('bar');
    +---------+----------+
    | user_id | username |
    +---------+----------+
    |       1 | bar      |
    +---------+----------+
    1 row in set (0.02 sec)
    
    $sqlCmd = sprintf("call insert_user('%s')", ...);
    

    Simple example:

    drop table if exists users;
    create table users
    (
    user_id int unsigned not null auto_increment primary key,
    username varchar(32) unique not null
    )
    engine=innodb;
    
    
    drop procedure if exists insert_user;
    
    delimiter #
    
    create procedure insert_user
    (
    in p_username varchar(32)
    )
    begin
    declare v_user_id int unsigned default 0;
    
     insert into users (username) values (p_username);
    
     set v_user_id = last_insert_id();
    
     -- do more stuff with v_user_id e.g. logs etc...
    
     select * from users where user_id = v_user_id;
    
    end#
    
    delimiter ;
    
    call insert_user('bar');
    
    0 讨论(0)
  • 2020-12-01 18:50

    No, it's not possible in MySQL (unlike PostgreSQL, SQL Server and PL/SQL in Oracle).

    You will have to do it in separate queries.

    0 讨论(0)
  • 2020-12-01 18:54

    Execute your insert statement and then you can do this:

    SELECT * FROM `items` WHERE `id`= LAST_INSERT_ID()
    
    0 讨论(0)
  • 2020-12-01 18:54

    You can do this using multiple statements if you like to choose that route. Firstly when you connect to your database make sure that multiple statements is set to true:

    var connection = mysql.createConnection({
        host: databaseHost,
        user: databaseUser,
        password: databasePassword,
        database: databaseName,
        multipleStatements: true
    });
    

    Then you can just define your sql as:

    var sql = "your insert statement; your select statement";
    

    Just separate individual statements using the semi colon. Your select result will be results[1] in this example.

    0 讨论(0)
提交回复
热议问题