【发布时间】:2014-11-17 07:58:58
【问题描述】:
我正在尝试使用两个表进行左连接,我需要首先获取所有用户 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 将空值替换为零。但是还是不行。请让我知道我做错了什么。
【问题讨论】:
标签: php laravel eloquent laravel-3