【发布时间】: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 和更多列。
我想选择表格中的所有行,此外我希望每个对象都包含一个计数器,这样我就知道该文本在表格中出现了多少次
但是,我不想对我的结果进行分组,并且还根据测试 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 子句之前发生的,所以我在计数中得到的数字是“文本”出现在我的整个表格中的数字。
【问题讨论】: