繁体   English   中英

Laravel查询获取不同值的出现

[英]Laravel query get occurrences of distinct values

编辑:通过在我的查询中添加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子句之前进行,因此计数中得到的数字就是“ text”出现在整个表中的数字。

这有点复杂,但是要这样做,您需要将表本身连接到文本列上,按ID进行分组,然后选择count。

这样的事情应该起作用...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM