Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select last record in the table

Tags:

php

mysql

yii2

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); 
like image 610
MaksimK Avatar asked Jan 12 '15 19:01

MaksimK


1 Answers

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.

like image 180
arogachev Avatar answered Sep 19 '22 08:09

arogachev