在15行

时间:2018-01-07 12:18:58

标签: php mysql

如果表中有15行,然后我添加了一个新行,有没有办法自动删除该表中的第一行?

所以它应该是这样的: ids 1-15,然后当我添加一个新ID:ids 2-16时,我再添加一个新ID:ids 3-17等等。

EDIT1: 我现在有这个代码,但它对我不起作用。

    $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');
    }

3 个答案:

答案 0 :(得分:2)

当你在表格中添加新行时,你应该删除像这样的最小ID

DELETE FROM myTable 
ORDER BY my_id
LIMIT 1;

确保idauto-increment

根据您的要求,首先计算总行数

SELECT COUNT(*) FROM tablename;

然后使用if条件

if($countRows >= 15)
{
   // execute delete query
}

答案 1 :(得分:2)

如果你只想在表格中保留15行,那么:

delete
from yourtable
where yourid < (select yourid
                from yourtable
                order by yourid desc
                limit 14, 1)

答案 2 :(得分:1)

一个想法是在INSERT本身中包含约束。

另一个想法是只允许UPDATE,如下所示:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table (ts TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP PRIMARY KEY,string VARCHAR(20) NOT NULL);

INSERT INTO my_table VALUES 
('2018-01-07 13:04:40 | one'),
('2018-01-07 13:04:45 | two'),
('2018-01-07 13:04:51 | three'),
('2018-01-07 13:04:57 | four'),
('2018-01-07 13:05:02 | five'),
('2018-01-07 13:05:07 | six'),
('2018-01-07 13:05:12 | seven'),
('2018-01-07 13:05:17 | eight'),
('2018-01-07 13:05:22 | nine'),
('2018-01-07 13:05:27 | ten'),
('2018-01-07 13:05:32 | eleven'),
('2018-01-07 13:05:38 | twelve'),
('2018-01-07 13:05:43 | thirteen'),
('2018-01-07 13:05:50 | fourteen'),
('2018-01-07 13:05:54 | fifteen');

UPDATE my_table SET ts = CURRENT_TIMESTAMP, string = 'sixteen' ORDER BY ts LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

SELECT * FROM my_table;
+---------------------+----------+
| ts                  | string   |
+---------------------+----------+
| 2018-01-07 13:04:45 | two      |
| 2018-01-07 13:04:51 | three    |
| 2018-01-07 13:04:57 | four     |
| 2018-01-07 13:05:02 | five     |
| 2018-01-07 13:05:07 | six      |
| 2018-01-07 13:05:12 | seven    |
| 2018-01-07 13:05:17 | eight    |
| 2018-01-07 13:05:22 | nine     |
| 2018-01-07 13:05:27 | ten      |
| 2018-01-07 13:05:32 | eleven   |
| 2018-01-07 13:05:38 | twelve   |
| 2018-01-07 13:05:43 | thirteen |
| 2018-01-07 13:05:50 | fourteen |
| 2018-01-07 13:05:54 | fifteen  |
| 2018-01-07 13:07:15 | sixteen  |
+---------------------+----------+
15 rows in set (0.00 sec)

mysql>