使用WHEN CASE的Cakephp查询

时间:2018-03-05 05:21:41

标签: cakephp case

我有以下查询。

$parents = $this->SurveyQuestion->find('all',array('fields' => array( 
                       'SurveyQuestion.id', 
                       '((CASE WHEN SurveyQuestion.tree_label%2="" THEN \'tree_label\' ELSE \'label\' END)) AS plabel' 
                   ),'conditions' => 
                array('`SurveyQuestion`.`id` <>' => $id), 'recursive' => -1));

我想要下面的结果。 如果它不是NULL,我想要来自tree_label列的结果,否则我想要来自label列的结果。 以上查询返回错误值。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

可能会帮助你

$parents = $this->SurveyQuestion->find('all',array('fields' => array( 
                       'SurveyQuestion.id', 
                       '((CASE WHEN SurveyQuestion.tree_label%2="" THEN SurveyQuestion.tree_label ELSE SurveyQuestion.label END)) AS plabel' 
                   ),'conditions' => 
                array('`SurveyQuestion`.`id` <>' => $id), 'recursive' => -1));

答案 1 :(得分:-1)

给你一个类似的例子,请尝试这样:

SELECT
COUNT(CASE WHEN published = 'Y' THEN 1 END) AS number_published,
COUNT(CASE WHEN published = 'N' THEN 1 END) AS number_unpublished
FROM articles

$query = $articles->find();
$publishedCase = $query->newExpr()
->addCase(
    $query->newExpr()->add(['published' => 'Y']),
    1,
    'integer'
);

$unpublishedCase = $query->newExpr()
->addCase(
    $query->newExpr()->add(['published' => 'N']),
    1,
    'integer'
);

 $query->select([
'number_published' => $query->func()->count($publishedCase),
'number_unpublished' => $query->func()->count($unpublishedCase)
]);

希望它有所帮助:)