我正在尝试在laravel查询构建器中执行此查询,但结果不一样。
select u.id as id,
u.name as name,
count(c.user_id) as casos,
cast(SUM(CASE WHEN c.status = 2 THEN 1 ELSE 0 END) AS SIGNED INTEGER) AS pendientes,
cast(SUM(CASE WHEN c.status = 0 THEN 1 ELSE 0 END) AS SIGNED INTEGER) AS enviados
from users u
left join casos c
on c.user_id = u.id
where u.lab_id = 2
and u.admin = 0
group by u.id
这是我的laravel查询:
User::select(
'users.id as id',
'users.name as name',
DB::raw("count(casos.user_id) as casos"),
DB::raw("cast(SUM(CASE WHEN casos.status = 2 THEN 1 ELSE 0 END) AS SIGNED INTEGER) AS pendientes"),
DB::raw("cast(SUM(CASE WHEN casos.status = 0 THEN 1 ELSE 0 END) AS SIGNED INTEGER) AS enviados"),
'users.created_at as created_at'
)
->leftJoin('casos', 'casos.user_id', '=', 'users.id')
->where('lab_id', 2)
->groupBy('user_id');
原始查询返回所有用户,即使没有casos,laravel只返回他们有casos的用户。我在laravel查询中做错了什么?
答案 0 :(得分:0)
将您的最后一行更改为:
->leftJoin('casos', 'casos.user_id', '=', 'users.id')
->where('users.lab_id', 2)
->where('users.admin', 0)
->groupBy('users.id');
缺少条件u.admin = 0
。您按casos.user_id
而不是users.id
进行分组。您不应按LEFT JOIN的右表分组。