如何有条件地 select 聚合函数 return 值?
How to conditionally select an aggregate function return value?
目前我正在这样询问最小值和最大值:
$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
])
// ...
另见
目前我正在这样询问最小值和最大值:
$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
])
// ...
另见