简体   繁体   中英

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); 

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.

PS Hardcoded id is a bad practice.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM