【问题标题】:SQL join left in laravel query builder在 laravel 查询生成器中留下 SQL 连接
【发布时间】:2018-03-17 11:03:43
【问题描述】:

我正在尝试在 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 查询中做错了什么?

【问题讨论】:

  • 有任何错误吗?
  • 没有错误,只是结果不同...
  • 也许你只是错过了->where('users.admin', 0)
  • 顺便说一句:你为​​什么使用CAST?无需将 10 强制转换为整数。
  • 我使用 CAST 因为在开发环境中我使用 sqllite 并返回字符串

标签: php mysql laravel laravel-eloquent


【解决方案1】:

将最后几行更改为:

->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 的右表进行分组。

【讨论】:

    猜你喜欢
    • 2020-06-20
    • 2022-01-20
    • 2014-05-13
    • 2020-03-12
    • 1970-01-01
    • 2015-12-05
    • 2014-12-06
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多