Add previous row in mysql

4

I have a launch line, in which this line would need to receive the value of the previous line +1, some example of how to do this?

Table structure:

CREATE TABLE 'lancamento' ( 
'data' VARCHAR(10) NOT NULL, 
'descricao' VARCHAR(30) NOT NULL, 
'debito' DOUBLE(20,2) NOT NULL, 
'credito' DOUBLE(20,2) NOT NULL, 
'saldo' DOUBLE(20,2) NOT NULL, 
'lancamento' DOUBLE(20,2) NOT NULL 
) ENGINE=INNODB
    
asked by anonymous 04.10.2017 / 14:44

2 answers

1

MySQL already has a native option with this goal, just inform that it should use AUTO INCREMENTO at the time of creating the table, since it was not done this option can also be informed by ALTER TABLE :

ALTER TABLE 'lancamento'   
  CHANGE 'lancamento' 'lancamento' INT NOT NULL AUTO_INCREMENT  FIRST,
  CHANGE 'data' 'data' VARCHAR(10) CHARSET latin1 COLLATE latin1_swedish_ci NOT NULL  AFTER 'lancamento', 
  ADD PRIMARY KEY ('lancamento');

From now on, you do not need to enter the lancamento field at the time of giving INSERT and automatically MySQL will generate an increased number:

INSERT INTO 'lancamento' ('data', 'descricao', 'debito', 'credito', 'saldo')
VALUES ('', '', 0, 0, 0);
    
04.10.2017 / 16:15
0

I imagine you will have to first query the value you want to add 1 and save in a variable, making a select pa get the value.

Lock tables TABELA write;

$VALORSALVO = SELECT VALORATUAL FROM TABELA ;

Taking the value you want, you must use the variable you received by adding 1 to it, making a common insert.

INSERT INTO TABELA( ID, VALORNOVO, )
VALUES ( 3 , $VALORSALVO+1);

unlock tables;

Notice that I traced the table ( Lock tables TABELA write ), during the operation to ensure we can do the proposed logic and finally unlocked ( unlock tables; ).

    
04.10.2017 / 14:48