我正在尝试使用两个表进行左连接,其中我需要首先获取所有用户ID和名称,以满足每个用户的第二个表中的条件和总行数。如果用户在第二个表中没有行,则它必须为null或零。
这是我雄辩的查询。
$users->where('users.access_type', '=', 'type1')->orwhere('users.access_type', '=', 'type2')
->leftJoin(DB::raw("(SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table"), function($leftJoin) {
$leftJoin->on('temp_table.user_id', '=', 'users.user_id');
})->select(DB::raw('users.user_id, users.name, temp_table.count as count'))->orderBy('count')->get();
不会返回具有空计数值的用户。相反,它返回最少计数的用户。我打印了查询日志并复制了上述查询的原始查询,填充了值并执行了。它完美地工作并且还返回具有空条目的用户。除了添加值之外,不对从查询日志获取的查询进行任何更改。复制下面的原始查询。
select users.user_id, users.name, temp_table.count as count from `users` left join (SELECT user_id, COUNT(*) as count FROM table2 WHERE date > '2014-09-17 16:30:04' GROUP BY user_id) temp_table on `temp_table`.`user_id` = `users`.`user_id` where `users`.`access_type` = 'type1' or `users`.`access_type` = 'type2' order by `count` asc
我尝试使用as user
更改user_id字段的列名。还尝试使用IFNULL
将零值替换为零。但仍然没有去。请让我知道我做错了什么。
答案 0 :(得分:0)
在您的Eloquent查询中,您需要将最后一个函数调用...->first()
替换为...->get()
,以便检索所有结果,而不是仅检索第一个结果。