简体   繁体   中英

Laravel query get occurrences of distinct values

Edit: solved by adding where clause to my query

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

I have a table with a few columns - id, text, test_id, is_private and a few more columns.

I want to select all rows in the table, in addition I want each object to include a counter so I know how many times that text appears in the table

Tried to follow this post: http://www.tagwith.com/question_164722_count-occurrences-of-distinct-values-using-laravel-query-builder

But, I don't want to group my result, and also use a where clause according to test id

So for example for the following entries, I want to select entries where test_id=700:

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

Output should be something like:

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

Using the following query:

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

I'm not getting the correct results, it looks like the counting is happening before the where clause, so the numbers I get in the count are the number that 'text' appears in my entire table.

It's a little complicated, but to do so, you would need to join the table on itself on the text columns, group by the id's, and select count.

Something like this should work...

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

Or the raw SQL

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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