Yii2 select 按最大日期?
Yii2 select by max date?
假设我有 table A 及其在 yii2 中的活动记录,将具有最大创建日期的记录加载到模型的最佳方法是什么。
这是查询:
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, according to the 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().
试试这个
$model = A::find()->orderBy("created_date DESC")->one();
$maxdate=A::find()->max('created_date');
假设我有 table A 及其在 yii2 中的活动记录,将具有最大创建日期的记录加载到模型的最佳方法是什么。
这是查询:
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, according to the official Yii documentation 所指出的:
Neither
yii\db\ActiveRecord::findOne()
noryii\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().
试试这个
$model = A::find()->orderBy("created_date DESC")->one();
$maxdate=A::find()->max('created_date');