【问题标题】:Cakephp query with WHEN CASE使用 WHEN CASE 进行 Cakephp 查询
【发布时间】:2018-03-05 05:21:41
【问题描述】:

我有以下查询。

$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 列的结果,否则我想要来自标签列的结果。 上面的查询返回错误的值。有人可以帮忙吗?

【问题讨论】:

标签: cakephp case


【解决方案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)
]);

希望对你有帮助:)

【讨论】:

【解决方案2】:

也许这会对你有所帮助

$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));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-01
    • 2014-11-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 2017-08-15
    • 1970-01-01
    相关资源
    最近更新 更多