sql >> Base de Datos >  >> RDS >> Mysql

¿Cómo crear dos columnas de incremento automático en MySQL?

No tengo idea de por qué necesita dos columnas que incrementan automáticamente los valores, no tiene sentido... pero si insiste,
Puede lograrlo en un UDF o SP de esta manera, tiene varias columnas que incrementan automáticamente un valor.

EJEMPLO #1:PROCEDIMIENTO ALMACENADO (SP)


Mesa

CREATE TABLE tests (
    test_id INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    test_num INT(10) NULL,
    test_name VARCHAR(10) NOT NULL
);



Procedimiento almacenado

DELIMITER $$
CREATE PROCEDURE autoInc (name VARCHAR(10))
    BEGIN
        DECLARE getCount INT(10);

        SET getCount = (
            SELECT COUNT(test_num)
            FROM tests) + 1;

        INSERT INTO tests (test_num, test_name)
            VALUES (getCount, name);
    END$$
DELIMITER ;



Llame al SP

CALL autoInc('one');
CALL autoInc('two');
CALL autoInc('three');



Mira la tabla

SELECT * FROM tests;

+---------+----------+-----------+
| test_id | test_num | test_name |
+---------+----------+-----------+
|       1 |       1  | one       |
|       2 |       2  | two       |
|       3 |       3  | three     |
+---------+----------+-----------+



EJEMPLO #2:FUNCIÓN DEFINIDA POR EL USUARIO (UDF)


Mesa
CREATE TABLE tests (
    test_id INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    test_num INT(10) NULL,
    test_name VARCHAR(10) NOT NULL
);



Función definida por el usuario

DELIMITER $$
CREATE FUNCTION autoInc ()
    RETURNS INT(10)
    BEGIN
        DECLARE getCount INT(10);

        SET getCount = (
            SELECT COUNT(test_num)
            FROM tests) + 1;

        RETURN getCount;
    END$$
DELIMITER ;



Insertar usando UDF

INSERT INTO tests (test_num, test_name) VALUES (autoInc(), 'one');
INSERT INTO tests (test_num, test_name) VALUES (autoInc(), 'two');
INSERT INTO tests (test_num, test_name) VALUES (autoInc(), 'three');



Mira la tabla

SELECT * FROM tests;

+---------+----------+-----------+
| test_id | test_num | test_name |
+---------+----------+-----------+
|       1 |       1  | one       |
|       2 |       2  | two       |
|       3 |       3  | three     |
+---------+----------+-----------+

Estos han sido probados y verificados. Yo personalmente usaría la función, es más flexible.