【问题标题】:Using DISTINCT inside a COUNT with CakePHP 3在带有 CakePHP 3 的 COUNT 中使用 DISTINCT
【发布时间】:2015-10-20 16:10:37
【问题描述】:

我是 CakePHP 3 的新手,我想知道如何在 COUNT 中使用 DISTINCT,例如以下 SQL 查询。

SELECT `column_one`, COUNT(DISTINCT `column_two`) FROM `table` GROUP BY `column_one`

【问题讨论】:

    标签: sql cakephp cakephp-3.0


    【解决方案1】:

    你可以这样做

    $query = $table->find()
    ->select([
        'column_one',
        'count' => "COUNT(DISTINCT `column_two`)"
    ])
    ->group(['column_one']);
    

    但是如果你想使用 cakephp sql 函数你可以这样做

    ...
    'count' => $query->func()->count('DISTINCT `column_two`')
    ....
    

    【讨论】:

    • 如果你包含一个使用原生CakePHP count() 函数的完整解决方案会更清楚一些;从您的解决方案中,$query 需要单独实例化并不是很明显。像这样: $query = $table->find('all'); $query = $query->select([ 'column_one', 'count' => $query->func()->count('DISTINCT column_two')]);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-05
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多