簡體   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