SQL 在 laravel 查询生成器中加入左侧
SQL join left in laravel query builder
我正在尝试在 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');
原始查询 return 所有用户即使没有 casos,laravel return 只有用户有 casos。我在 laravel 查询中做错了什么?
将最后几行更改为:
->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 的右侧 table 分组。
我正在尝试在 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');
原始查询 return 所有用户即使没有 casos,laravel return 只有用户有 casos。我在 laravel 查询中做错了什么?
将最后几行更改为:
->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 的右侧 table 分组。