Cómo obtener el siguiente id de incremento automático en mysql


Cómo obtener el siguiente id en mysql para insertarlo en la tabla

INSERT INTO payments (date, item, method, payment_code)
VALUES (NOW(), '1 Month', 'paypal', CONCAT("sahf4d2fdd45", id))
 91
Author: Markus Malkusch, 2011-07-20

18 answers

Uso LAST_INSERT_ID() desde su consulta SQL.

O

También puede utilizar mysql_insert_id() para conseguirlo usando PHP.

 13
Author: Sarfraz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-20 11:52:34

Puedes usar

SELECT AUTO_INCREMENT
FROM information_schema.tables
WHERE table_name = 'table_name'
AND table_schema = DATABASE( ) ;

O si no desea utilizar information_schema puede utilizar este

SHOW TABLE STATUS LIKE 'table_name'
 221
Author: ravi404,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-15 07:04:18

Puede obtener el siguiente valor de auto-incremento haciendo:

SHOW TABLE STATUS FROM tablename LIKE Auto_increment
/*or*/
SELECT `auto_increment` FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = 'tablename'

Tenga en cuenta que debe no usar esto para alterar la tabla, use una columna auto_increment para hacerlo automáticamente en su lugar.
El problema es que last_insert_id() es retrospectivo y, por lo tanto, se puede garantizar dentro de la conexión actual.
Este bebé es prospectivo y, por lo tanto, no es único por conexión y no se puede confiar en él.
Solo en una base de datos de conexión única funcionaría, pero una sola conexión las bases de datos de hoy tienen la costumbre de convertirse en múltiples bases de datos de conexión de mañana.

 34
Author: Johan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-09 23:19:24

En PHP puedes probar esto:

$query = mysql_query("SELECT MAX(id) FROM `your_table_name`");
$results = mysql_fetch_array($query);
$cur_auto_id = $results['MAX(id)'] + 1;

O

$result = mysql_query("SHOW TABLE STATUS WHERE `Name` = 'your_table_name'");
$data = mysql_fetch_assoc($result);
$next_increment = $data['Auto_increment'];
 9
Author: Naresh Jain,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-19 10:09:41

La respuesta principal usa PHP MySQL_ para una solución, pensé que compartiría una solución actualizada de PHP MySQLi_ para lograr esto. No hay salida de error en este ejemplo!

$db = new mysqli('localhost', 'user', 'pass', 'database');
$sql = "SHOW TABLE STATUS LIKE 'table'";
$result=$db->query($sql);
$row = $result->fetch_assoc();

echo $row['Auto_increment'];

Inicia el siguiente incremento automático que viene en una tabla.

 9
Author: Hexchaimen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-05 07:26:00

Esto devolverá el valor de incremento automático para la base de datos MySQL y no comprobé con otras bases de datos. Tenga en cuenta que si está utilizando cualquier otra base de datos, la sintaxis de la consulta puede variar.

SELECT AUTO_INCREMENT 
FROM information_schema.tables
WHERE table_name = 'your_table_name'
     and table_schema = database();
 8
Author: Chaminda Bandara,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-14 08:20:13

Solución:

CREATE TRIGGER `IdTrigger` BEFORE INSERT ON `payments`
  FOR EACH ROW
BEGIN

SELECT  AUTO_INCREMENT Into @xId
    FROM information_schema.tables
    WHERE 
    Table_SCHEMA ="DataBaseName" AND
    table_name = "payments";

SET NEW.`payment_code` = CONCAT("sahf4d2fdd45",@xId);

END;

"DatabaseName" es el nombre de nuestra Base de datos

 6
Author: Angel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-09 11:19:40

Puede usar mysql trigger

 4
Author: Nick Pavluk,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-20 12:22:58

No puede usar el ID mientras inserta, ni lo necesita. MySQL ni siquiera conoce el ID cuando está insertando ese registro. Puedes guardar "sahf4d2fdd45" en la tabla payment_code y usar id y payment_code más adelante.

Si realmente necesita que su payment_code tenga el ID en él, ACTUALICE la fila después del insert para agregar el ID.

 3
Author: Jacob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-07-20 11:57:04

¿Para qué necesita el siguiente ID incremental?

MySQL solo permite un campo de auto-incremento por tabla y también debe ser la clave principal para garantizar la unicidad.

Tenga en cuenta que cuando obtenga el siguiente ID de inserción, puede que no esté disponible cuando lo use, ya que el valor que tiene solo está dentro del alcance de esa transacción. Por lo tanto, dependiendo de la carga en su base de datos, ese valor puede estar ya utilizado cuando llegue la siguiente solicitud.

Yo sugeriría que revise su diseño para asegurarse de que no necesita saber qué valor de incremento automático asignar a next

 3
Author: Stephen Senkomago Musoke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-09 12:11:48

Una consulta simple haría SHOW TABLE STATUS LIKE 'table_name'

 3
Author: Raa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-16 08:12:03

Tienes que conectarte a MySQL y seleccionar una base de datos antes de poder hacer esto

$table_name = "myTable"; 
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'"); 
$row = mysql_fetch_array($query); 
$next_inc_value = $row["AUTO_INCREMENT"];  
 2
Author: jondinham,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-07-30 13:53:48

Sugiero que reconsideres lo que estás haciendo. Nunca experimenté un solo caso de uso donde se requiere ese conocimiento especial. El siguiente id es un detalle de implementación muy especial y no contaría con que sea seguro para el ÁCIDO.

Realice una transacción simple que actualice su fila insertada con el último id:

BEGIN;

INSERT INTO payments (date, item, method)
     VALUES (NOW(), '1 Month', 'paypal');

UPDATE payments SET payment_code = CONCAT("sahf4d2fdd45", LAST_INSERT_ID())
     WHERE id = LAST_INSERT_ID();

COMMIT;
 2
Author: Markus Malkusch,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-01-05 07:58:10

Use " mysql_insert_id ()". mysql_insert_id() actúa sobre la última consulta realizada, asegúrese de llamar a mysql_insert_id () inmediatamente después de la consulta que genera el valor.

A continuación se muestra el ejemplo de uso:

<?php
    $link = mysql_connect('localhost', 'username', 'password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydb');

mysql_query("INSERT INTO mytable  VALUES('','value')");
printf("Last inserted record has id %d\n", mysql_insert_id());
    ?>

Espero que el ejemplo anterior sea útil.

 2
Author: sagarchavda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-07 11:28:37
mysql_insert_id();

Eso es todo:)

 1
Author: user3814281,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-22 21:40:26
SELECT id FROM `table` ORDER BY id DESC LIMIT 1

Aunque dudo de su productividad, pero es 100% confiable

 1
Author: Tebe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-21 05:36:49

Usando la respuesta de ravi404:

CREATE FUNCTION `getAutoincrementalNextVal`(`TableName` VARCHAR(50))
    RETURNS BIGINT
    LANGUAGE SQL
    NOT DETERMINISTIC
    CONTAINS SQL
    SQL SECURITY DEFINER
    COMMENT ''
BEGIN

    DECLARE Value BIGINT;

    SELECT
        AUTO_INCREMENT INTO Value
    FROM
        information_schema.tables
    WHERE
        table_name = TableName AND
        table_schema = DATABASE();

    RETURN Value;

END

Usando en su consulta de inserción, para crear un Hash SHA1. ex.:

INSERT INTO
    document (Code, Title, Body)
VALUES (                
    sha1( getAutoincrementalNextval ('document') ),
    'Title',
    'Body'
);
 0
Author: Paulo A. Costa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-27 09:46:12

Mejora de @ ravi404, en caso de que su desplazamiento de autoincremento NO SEA 1 :

SELECT (`auto_increment`-1) + IFNULL(@@auto_increment_offset,1) 
FROM INFORMATION_SCHEMA.TABLES
WHERE table_name = your_table_name
AND table_schema = DATABASE( );

(auto_increment-1) : el motor db parece considerar siempre un desplazamiento de 1. Por lo tanto, debe deshacerse de esta suposición, luego agregue el valor opcional de @ @ auto_increment_offset,o por defecto a 1 : IFNULL(@@auto_increment_offset, 1)

 0
Author: Olivier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 12:30:12