Is it possible to insert a new row at top of MySQL table?

后端 未结 5 839
别跟我提以往
别跟我提以往 2020-12-10 05:43

All rows in MySQL tables are being inserted like this:

1
2
3

Is there any way how to insert new row at a top of table so that table looks l

相关标签:
5条回答
  • 2020-12-10 06:15

    The order in which the results are returned when there's no ORDER BY clause depends on the RDBM. In the case of MySQL, or at least most engines, if you don't explicitly specify the order it will be ascending, from oldest to new entries. Where the row is located "physically" doesn't matter. I'm not sure if all mysql engines work that way though. I.e., in PostgreSQL the "default" order shows the most recently updated rows first. This might be the way some of the MySQL engines work too.

    Anyway, the point is - if you want the results ordered - always specify sort order, don't just depend on something default that seems to work. In you case you want something trivial - you want the users in descending order, so just use:

    SELECT * FROM users ORDER BY id DESC
    
    0 讨论(0)
  • 2020-12-10 06:22

    I know that a lot of time has passed since the above question was asked. But I have something to add to the comments:

    I'm using MySQL version: 5.7.18-0ubuntu0.16.04.1

    When no ORDER BY clause is used with SELECT it is noticeable that records are displayed, regardless of the order in which they are added, in the table's Prime Key sequence.

    0 讨论(0)
  • 2020-12-10 06:23

    Maybe if you add the id 'by hand', and give it a negative value, but i (and probably nobody) would recommend you to do that:

    1. Regular insert, e.g.

      insert into t values (...);

    2. Update with set, e.g.

      update t set id = -id where id = last_insert_id();

    0 讨论(0)
  • 2020-12-10 06:27

    Normally you specify a auto_incrementing primary key.

    However, you can just specify the primary key like so:

    CREATE TABLE table1 (
      id signed integer primary key default 1, <<-- no auto_increment, but has a default value
      other fields .....
    

    Now add a BEFORE INSERT trigger that changes the primary key.

    DELIMITER $$
    
    CREATE TRIGGER ai_table1_each BEFORE INSERT ON table1 FOR EACH ROW
    BEGIN
      DECLARE new_id INTEGER;
      SELECT COALESCE(MIN(id), 0) -1 INTO new_id FROM table1;
      SET NEW.id = new_id;
    END $$
    
    DELIMITER ; 
    

    Now your id will start at -1 and run down from there.
    The insert trigger will make sure no concurrency problems occur.

    0 讨论(0)
  • 2020-12-10 06:33

    I think you just need to make sure that if you always need to show the latest data first, all of your indexes need to specify the date/time field first, and all of your queries order by that field first.

    If ORDER BY is slowing everything down then you need to optimise your queries or your database structure, i would say.

    0 讨论(0)
提交回复
热议问题