【问题标题】:Laravel query get occurrences of distinct valuesLaravel 查询获取不同值的出现
【发布时间】:2019-07-10 19:22:52
【问题描述】:

编辑:通过向我的查询添加 where 子句解决

    ->where('first.test_id',$test_id)
    ->where('second.test_id',$test_id)
    ->where('first.is_private',0)
    ->where('second.is_private',0)

我有一个包含几列的表 - id、text、test_id、is_private 和更多列。

我想选择表格中的所有行,此外我希望每个对象都包含一个计数器,这样我就知道该文本在表格中出现了多少次

尝试关注此帖:http://www.tagwith.com/question_164722_count-occurrences-of-distinct-values-using-laravel-query-builder

但是,我不想对我的结果进行分组,并且还根据测试 id 使用 where 子句

例如,对于以下条目,我想选择 test_id=700 的条目:

id text test_id
1  abc  700
2  abc  700
3  aaa  700
4  abc  701

输出应该是这样的:

$rows[0] = {id = 1, text='abc',count=2}
$rows[1] = {id = 2, text='abc',count=2}
$rows[2] = {id = 3, text='aaa',count=1}

使用以下查询:

    return DB::table('comments AS first')
            ->select(['first.*',DB::raw('count(first.text)')])
            ->join('comments as second','first.text','=','second.text')
            ->where('first.test_id',$test_id)
            ->where('first.is_private',0)
            ->orderBy('first.question_number', 'asc')
            ->orderBy('first.subquestion_number', 'asc')
            ->groupBy('first.id')
            ->get();

我没有得到正确的结果,看起来计数是在 where 子句之前发生的,所以我在计数中得到的数字是“文本”出现在我的整个表格中的数字。

【问题讨论】:

    标签: php mysql laravel


    【解决方案1】:

    这有点复杂,但要这样做,您需要在文本列上加入表格,按 id 分组,然后选择计数。

    这样的东西应该可以工作......

        $results = DB::table('test as a')
        ->select(['a.id', 'a.text', DB::raw('count(*)')])
        ->join('test as b', 'a.text', '=', 'b.text')
        ->groupBy('a.id')
        ->get();
    

    或原始 SQL

    SELECT 
        a.id,
        a.text, 
        COUNT(*)
    FROM test A
    INNER JOIN test B ON a.text = b.text
    GROUP BY a.id;
    

    【讨论】:

    • thx,1.您需要为表别名添加 AS,2.我在查询中使用 select 子句,我认为计数发生在 where 所以我得到错误的计数结果之前
    • 我已经更新了我的答案以适当地使用表别名。计数不应该在 where 子句之前发生,那没有任何意义。使用您提供的数据,查询工作。您在问题中包含的信息越多,我们就越有可能帮助您找到可行的解决方案。
    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 1970-01-01
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多