MySQL current_insert_id ()? (Not last_insert_id ())

I am inserting a row with a char column for a hash based on (among other things) the row id.

I know that I can insert it, get insert_id, calculate the hash and update it.

Does anyone know a way to do this in a single request? You will need insert_id strings during insertion. This is completely impossible, or is there something like current_insert_id () ...

Thanks!

+3
source share
4 answers

No, in MySQL there is no function that gives you current_insert_id().

ID AUTO_INCREMENT MySQL - INSERT, last_insert_id(). , UPDATE , , .

:

  • INSERT , AUTO_INCREMENT. , . UUID().

    SET @id = SELECT UUID();
    INSERT INTO MyTable (id, hash) VALUES (@id, hash(@id...));
    
  • -.

+11

, MySQL , - :

<?php

$query = mysql_query("SHOW TABLE STATUS LIKE 'MyTable'");
$row = mysql_fetch_assoc($query);
$next_id = $row['Auto_increment'];

?>

... SQL.

EDIT: , .

+2

You can request the following value for next use from the table information_schema. TABLEScolumn AUTO_INCREMENT. (Did you tune in to the race?)

+1
source

When I insert, I do something like this:

INSERT INTO table (col1,col2) VALUES (data1,data2);SELECT LAST_INSERT_ID()

and just run the query as I received the data. In VB.NET syntax (if you have a file MySql.Data.MySqlClient.dll):

Dim sql As String = "[sql string above]"
Dim dr As MySqlDataReader = YourRetrieveDataFunction(sql)

dr.Read()
yourObjectInstance.ID = dr(0)
dr.Close

These are technically two queries, but only one hit in the database :)

0
source

Source: https://habr.com/ru/post/1708499/


All Articles