MaksimK
MaksimK

Reputation: 183

Select last record in the table

How to select last record (that is having MAX(id)) from the table?
Next statement works OK, but selects the first record:

$statistics = SystemStatisticsHistory::findOne(1); 

Upvotes: 14

Views: 24261

Answers (2)

Burhan Ibrahimi
Burhan Ibrahimi

Reputation: 377

Optimised one

SystemStatisticsHistory::find()->select(['id'=>'MAX(`id`)'])->one()->id;

OR if you want increase by number

SystemStatisticsHistory::find()->select(['id'=>'( MAX(`id`)+ 1) '])->one()->id;

Upvotes: 0

arogachev
arogachev

Reputation: 33538

To get the model with max id you can apply reverse order and limit to one.

SystemStatisticsHistory::find()->orderBy(['id' => SORT_DESC])->one();

Another option is to use subselect with max like so:

SystemStatisticsHistory::find()
    ->where(['id' => SystemStatisticsHistory::find()->max('id')])
    ->one();

There are some nuances using last option, check this question.

You can check the documentation for max() here.

I personally prefer using first variation.

To get the first record, just change the order direction to SORT_ASC in first query and max() to min() in second query.

P.S. Hardcoded id is a bad practice.

Upvotes: 30

Related Questions