MySQL table with fixed number of rows?

2019-01-29 10:14发布

I have table documents (id, name, time). Is there a special sql command to set table limit by 10 rows?

标签: mysql sql row
3条回答
Evening l夕情丶
2楼-- · 2019-01-29 10:37

So, if you have a table like this:

CREATE TABLE documents (
  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  `name` VARCHAR( 99 ) NOT NULL,
  `time` DATETIME NOT NULL
) ENGINE = MYISAM

then you can use this horrible query to limit row numbers by recycling the row having the lowest id field:

INSERT INTO documents (id,name,time)
  SELECT
    IF( (SELECT COUNT(*) FROM documents) < 3 -- max row number you allow
       ,NULL -- just use autoincrement id
       ,(SELECT MIN(id) FROM documents) -- update row with smallest id
    ),
    -- your values to insert
    'name'
    ,'2011-11-11'
  ON DUPLICATE KEY UPDATE
    id   = (SELECT MAX(id)+1 FROM documents) -- new id
    -- your values again, now for update
   ,name = 'name'
   ,time = '2011-11-11'

Somebody please confirm if this query is atomic, i think it is, but who knows…

查看更多
Melony?
3楼-- · 2019-01-29 10:51

If you just want to display the "latest 10 generated documents", no need for a separate table. Just use a query on your existing table:

SELECT id, name, `time`
FROM documents
ORDER BY `time` DESC
LIMIT 10
查看更多
ら.Afraid
4楼-- · 2019-01-29 10:59

no you could not set a limit on the mysql table, you can achive this with trigger that delete rows.

查看更多
登录 后发表回答