简体   繁体   English

选择表格中的最后一条记录

[英]Select last record in the table

How to select last record (that is having MAX(id) ) from the table? 如何从表中选择最后一条记录(即MAX(id) )?
Next statement works OK, but selects the first record: Next语句工作正常,但选择第一条记录:

$statistics = SystemStatisticsHistory::findOne(1); 

To get the model with max id you can apply reverse order and limit to one. 要获得具有最大id的模型,您可以应用逆序并限制为1。

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

Another option is to use subselect with max like so: 另一种选择是使用subselect和max如下所示:

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 . 您可以在此处查看max()的文档。

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. 要获取第一条记录,只需在第一个查询中将顺序方向更改为SORT_ASC在第二个查询SORT_ASC max()更改为min()

PS Hardcoded id is a bad practice. PS Hardcoded id是一种不好的做法。

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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