gpt4 book ai didi

mysql - Yii2 按最大日期选择?

转载 作者:可可西里 更新时间:2023-11-01 06:31:33 27 4
gpt4 key购买 nike

假设我在 yii2 中有表 A 及其事件记录,将具有最大创建日期的记录加载到模型的最佳方法是什么。

这是查询:

     select * 
from A
where created_date = (
select max(created_date) from A
)

现在我首先获取最大日期,然后在另一个数据库访问中使用它,即:

    $max = A::find()->select("created_date)")->max();
$model = A::find()->where("created_date = :date",[":date"=>$max])->one();

我确信这可以通过一次访问数据库来完成,但我不知道如何做。

请帮忙。

最佳答案

您的查询相当于:

SELECT * FROM A ORDER BY created_date DESC LIMIT 1;

您可以按 created_date 降序排列您的记录,并获得第一条记录,即:

$model = A::find()->orderBy('created_date DESC')->limit(1)->one();

为什么 limit(1)?正如 nicolascolman 指出的那样, 根据 official Yii documentation :

Neither yii\db\ActiveRecord::findOne() nor yii\db\ActiveQuery::one() will add LIMIT 1 to the generated SQL statement. If your query may return many rows of data, you should call limit(1) explicitly to improve the performance, e.g., Customer::find()->limit(1)->one().

关于mysql - Yii2 按最大日期选择?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28577991/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com