Is it possible to select the last (by the time of adding to the table) record in the table, if there is no time to add the record to the field?

For example, I have an sms_map table with two fields, sms_in_id and sms_out_id , and the following query:

 SELECT * FROM `sms_map` WHERE `sms_out_id` = 3251; 

returns the following result:

2521 3251

3221 3251

3216 3251

I would like to get the latest entry. The query with sorting does not suit me, since the query:

 SELECT * FROM `sms_map` WHERE `sms_out_id` = 3251 ORDER BY `sms_in_id` DESC LIMIT 1; 

returns the last record by the field value, and not by the time the record was added to the table.

  • Without ORDER BY, no order of output of the SELECT results is guaranteed and, moreover, may differ from launch to launch. Accordingly, if there are no data in the table, on the basis of which the desired sorting can be obtained, the answer to the question is no .. - Yaant

2 answers 2

Not. It's impossible. You need to have either the "add time" field or the auto-increment field

    I accepted the answer above and I understand that this is the RIGHT answer. But suddenly, somebody will have the same situation as mine, when the table has already been created, and neither the "add time" field nor the auto-increment field is in the table ... And you need to select the last entry in the table at least with most likely (since usually the rows are returned in the same order as they were inserted, but only until the update or delete operation is applied to the table).

    So if there was no update or delete operation, then the probability of the correct result will be high. In this case, the following can help:

     SET @num = (SELECT COUNT(*) FROM `sms_map` WHERE `sms_out_id` = 3251); SELECT * FROM ( SELECT *, @rownum := @rownum + 1 AS rank FROM (SELECT * FROM `sms_map` WHERE `sms_out_id` = 3251) t, (SELECT @rownum := 0) r ) d WHERE rank = @num;