gpt4 book ai didi

mysql - 如何有条件地选择聚合函数返回值?

转载 作者:行者123 更新时间:2023-11-30 22:05:17 26 4
gpt4 key购买 nike

目前我正在这样询问最小值和最大值:

$query = $query
->where(['date >=' => $today])
->select([
'minvalue' => $this->Daten->find()->func()->min('brennstoff'),
'maxvalue' => $this->Daten->find()->func()->max('brennstoff')
])
->hydrate(false)
->toArray();

有时最小值或最大值可能是NULL,所以不会有结果;但我想给出 0(零)。

在 SQL 中,我会使用 IF(MIN(value), MIN(value), 0))。但是如何在 ORM 语法中翻译它呢?

最佳答案

IF 是 MySQL 特有的,我建议改用 CASE 表达式,CakePHP 支持的所有 SQL 方言都可以理解它。

虽然查询构建器可用于创建任何类型的 SQL 函数调用,只需通过函数构建器调用具有相同名称的魔术方法,例如:

$minValue = $query->func()->IF([
$query->newExpr()->isNotNull($query->func()->min('brennstoff')),
$query->func()->min('brennstoff'),
0
]);

$maxValue = $query->func()->IF([
$query->newExpr()->isNotNull($query->func()->max('brennstoff')),
$query->func()->max('brennstoff'),
0
]);

IFNULL 更紧凑:

$minValue = $query->func()->IFNULL([
$query->func()->min('brennstoff'),
0
]);

$maxValue = $query->func()->IFNULL([
$query->func()->max('brennstoff'),
0
]);

CASE 表达式有具体的辅助方法:

$minValue = $query
->newExpr()
->addCase(
[$query->newExpr()->isNotNull($query->func()->min('brennstoff'))],
[$query->func()->min('brennstoff'), 0],
[null, 'integer']
);

$maxValue = $query
->newExpr()
->addCase(
[$query->newExpr()->isNotNull($query->func()->max('brennstoff'))],
[$query->func()->max('brennstoff'), 0],
[null, 'integer']
);

$query = $query
->select([
'minvalue' => $minValue,
'maxvalue' => $maxValue
])
// ...

另见

关于mysql - 如何有条件地选择聚合函数返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980953/

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