MySQL table with fixed number of rows?

前端 未结 3 463
失恋的感觉
失恋的感觉 2020-12-22 08:58

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

相关标签:
3条回答
  • 2020-12-22 09:07

    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…

    0 讨论(0)
  • 2020-12-22 09:08

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

    0 讨论(0)
  • 2020-12-22 09:32

    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
    
    0 讨论(0)
提交回复
热议问题