laravel 如何选择重复的行并按两列分组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31395738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to select duplicate rows and group by two columns
提问by Billy
I have the following table:
我有下表:
ID|user_id|group_id|subject |book_id
1| 2 |3 |history |1
2| 4 |3 |history |1
3| 5 |3 |art |2
4| 2 |3 |art |2
5| 1 |4 |sport |5
I would like to list all rows for group 3(id) that have duplicate rows with the same subject_id and book_id. The subject and book_id is what would determine the 2 or more rows to be duplicate.
我想列出组 3(id) 的所有行,这些行具有具有相同 subject_id 和 book_id 的重复行。主题和 book_id 将确定要重复的 2 行或更多行。
I would like my distinct results to look like this:
我希望我的独特结果如下所示:
|subject |book_id|
|history |1 |
|art |2 |
Using either query builder or eloquent
使用查询构建器或 eloquent
回答by peterm
A SQL query to get the desired result may look
获得所需结果的 SQL 查询可能看起来
SELECT subject, book_id
FROM table1
WHERE group_id = 3
GROUP BY subject, book_id
HAVING COUNT(*) > 1
Here is a SQLFiddledemo
这是一个SQLFiddle演示
Now the same using the Laravel Query Builder
现在同样使用 Laravel Query Builder
$duplicates = DB::table('table1')
->select('subject', 'book_id')
->where('group_id', 3)
->groupBy('subject', 'book_id')
->havingRaw('COUNT(*) > 1')
->get();