Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL delete first row when new is added when at 15 rows

Tags:

php

mysql

When there are 15 rows in a table and then i add a new row, is there a way to automatically delete the first row in that table?

so it should be like this: ids 1-15 , then when i add a new one: ids 2-16 ,then again i add a new one: ids 3-17 and so on.

edit1: i now have this code but it doesn't work for me.

    $this->db->select('count(*)');
    $this->db->from('chat');

    $countChat = $this->db->get();

    if ($countChat >= '16') {
        $this->db->delete();
        $this->db->from('chat');
        $this->db->order_by('id');
        $this->db->limit('1');
    }
like image 428
Smokey Avatar asked Dec 03 '25 20:12

Smokey


1 Answers

If you only want to keep 15 rows in the table in total, then:

delete
from yourtable
where yourid < (select yourid
                from yourtable
                order by yourid desc
                limit 14, 1)
like image 167
Lajos Arpad Avatar answered Dec 05 '25 10:12

Lajos Arpad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!