我有这个查询,它基本上列出了两个用户共有的主题。
$subcommon= SubjectUser::selectRaw('topic_id, count(topic_id) AS aggregate')
->whereIn('user_id', [4, 2])->groupBy('topic_id')
->having('aggregate','>',1)->get();
例如,下面表的查询结果将是
{"topic_id":3,"aggregate":1}
tableone
id|user_id|topic_id
1|2 |3
2|4 |3
3|5 |1
我有另一个表(table2),也有topic_id,我想加入,以便我从第二个表中获得第2行的查询结果。我该怎么做呢?
tabletwo
id|group_id|topic_id
1|6 |2
2|7 |3
3|7 |1
DB::table('tableone')->join('tabletwo', function($join) {
$join->on(tableone.topic_id, '=', tabletwo.topic_id);
})->get();
try this,
$subcommon= DB::table('tableone')
->selectRaw('topic_id, count(topic_id) AS aggregate')
->join('tabletwo','tabletwo.topic_id', '=', 'tableone.topic_id')
->whereIn('user_id', [4, 2])
->groupBy('tableone.topic_id')
->having('aggregate','>',1)
->get();