MySQL - Select the last inserted row easiest way

后端 未结 9 1874
误落风尘
误落风尘 2020-11-30 09:56

I simply need to select the last entered row specified by condition, e.g:

SELECT ID from bugs WHERE user=Me

I need to return only the very

相关标签:
9条回答
  • 2020-11-30 10:07

    One way to accomplish that is to order you records and limit to 1. For example if you have the following table ('data').

        id | user | price
       -------------------
        1  |  me  | 40.23
        2  |  me  | 10.23
    

    Try the following sql query

      select * from data where user='me' order by id desc limit 1
    
    0 讨论(0)
  • 2020-11-30 10:09
    SELECT * FROM `table_name` 
    ORDER BY `table_name`.`column_name` DESC
    LIMIT 1 
    
    0 讨论(0)
  • 2020-11-30 10:10
    MySqlCommand insert_meal = new MySqlCommand("INSERT INTO meals_category(Id, Name, price, added_by, added_date) VALUES ('GTX-00145', 'Lunch', '23.55', 'User:Username', '2020-10-26')", conn);
    if (insert_meal .ExecuteNonQuery() == 1)
    {
        long Last_inserted_id = insert_meal.LastInsertedId;
        MessageBox.Show(msg, "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Failed to save meal");
                }
    
    0 讨论(0)
  • 2020-11-30 10:19

    It would be best to have a TIMESTAMP column that defaults to CURRENT_TIMESTAMP .. it is the only true predictive behavior you can find here.

    The second-best thing you can do is ORDER BY ID DESC LIMIT 1 and hope the newest ID is the largest value.

    0 讨论(0)
  • 2020-11-30 10:20

    In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

    If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.

    0 讨论(0)
  • 2020-11-30 10:21
    SELECT MAX(ID) from bugs WHERE user=Me
    
    0 讨论(0)
提交回复
热议问题