我有两个要合并的表,将它们合并后,我要通过在联合中使用的一列进行分组
这是我尝试的内容:
$issuance = DB::table('issuance as i')
->select('i.issue_to as stud_id', 'i.created_on');
$stud= DB::table('transfer as t')
->select('t.transfer_to as stud_id', 't.created_on')
->union($issuance)
->select('stud_id', 'created_on', DB::raw('COUNT(*) as total_asset'))
->groupBy('stud_id')
->orderBy('created_on', 'DESC')->get();
这是我尝试过的MySQL查询
"(select `stud_id`, `created_on`, COUNT(*) as total_asset from `transfer` as
`t` group by `stud_id`) union (select `i`.`issued_to` as `stud_id`, `i`.`created_on` from
`issuance` as `i`) order by `created_on` desc"
我在MySQL中真正想要的是这样的:
select stud_id, count(*) from ((select `t`.`transfered_to` as `stud_id`,
`t`.`created_on` from `transfer` as `t`) union (select `i`.`issued_to` as
`stud_id`, `i`.`created_on`, COUNT(*) as asset from `issuance` as `i`)) as t
group by stud_id order by `created_on` desc
感谢您的帮助
答案 0 :(得分:0)
//尝试这个示例,它将为您提供帮助
$ query1 = DB :: table('table1')-> where(....);
$ query2 = DB :: table('table2')-> where(....);
$ data = DB :: select(DB :: raw('id,MAX(created_at)as max_created_at')> union($ query1)-> union($ query2)-> orderBy('max_created_at')-> groupBy('id')-> get();