Erase all information in the table the last inserted id

2

How do I delete the table in the database all data, in php, by the last id inserted? For example in the table the last ID is 37, where it has the name, age, etc ..., I want to delete all of this ID, make that line disappear. My question is not delete from ... where id='37' , but if I did not know that the last id entered was 37

    
asked by anonymous 24.05.2018 / 12:27

2 answers

2

There are some ways to get the last ID inserted into a table.

If you are using a sequence , you can query the sequence to get the current value, in oracle it would be sequence.CURRVAL , eg

select minhaSequence.CURRVAL from dual
/*OBS: dual é necessário aqui, não é o nome de uma "tabela"*/

If your ID is not a sequence , but it is a number that increments in some way, you can get the highest value from that column with max(col) , which for for example (IDs = 1, 2, 3, 4, 5, 6, 7) will return only the number 7.

select max(culuna_id) from nome_tabela;
/*aqui já precisa do nome da tabela*/

If your ID is neither a sequence nor a numerical , but have an order , you can collate / group some sorted selects and use ROWNUM to get the highest value of that column, in the example below (which I believe can be improved) for the IDs = a, b, c, d, e, f, will only return ID = f

select meu_id from
  ( select meu_id, rownum as num from
     (select meu_id from minha_tabela order by meu_id)
  )
where num = (select max(num1) from (select rownum as num1 from minha_tabela order by meu_id))
    
24.05.2018 / 13:06
1

It is possible to delete the last record in a simple way.

DELETE FROM NOMETABELA WHERE ID=(SELECT max(ID) FROM NOMETABELA)

Sorry, you're using MySQL, try this:

DELETE FROM NOMETABELA WHERE 
  id IN (SELECT * FROM (SELECT max(id) AS ID FROM NOMETABELA ) as T)

Additional information

link

    
24.05.2018 / 13:20