【问题标题】:leftJoin does not get all the rows in the LEFT tableleftJoin 没有得到 LEFT 表中的所有行
【发布时间】:2015-08-01 12:25:23
【问题描述】:

我有以下问题

#Query 1
$count = User::where('users.status', '=', 1)
    ->leftJoin('deposits', 'users.id', '=', 'deposits.user_id')
    ->select('users.*')
    ->groupBy('deposits.user_id')
    ->count();

# Count == 71


# Query 2
User::where('users.status', '=', 1)->count()

# Count == 89

请问为什么我没有得到用户表中的所有行?

最后,我想运行以下查询

$resellers = User::where('users.status', '=', UserStatus::getUserStatusAsInteger('reseller') )
                    ->leftJoin('deposits', 'users.id', '=', 'deposits.user_id')
                    ->where('deposits.status', '=', 'completed')
                    ->where('deposits.created_at', '>=',  \Carbon\Carbon::now()->subDays(25) )
                    ->having( DB::raw( 'sum( deposits.amount )') , '<', Settings::first()->min_reseller_deposit )
                    ->select('users.*',  DB::raw( 'sum( deposits.amount ) as `total_deposits`' ))
                    ->groupBy('users.id')
                    ->get();

谢谢

【问题讨论】:

    标签: sql laravel-4 eloquent


    【解决方案1】:

    即使您在表上left joining,您仍然使用join 条件并且查询将仅返回满足条件的行。由于right 表中没有与条件不匹配的行,因此您不会看到出现null 值。

    【讨论】:

    • 请你帮我做另一个查询,把所有用户连同他们的存款一起收集起来。如果他们有存款?
    • 我不确定..为什么您在声明中使用group by。你能试着把它取下来吗?
    • 如果我取消它,我会得到重复的行,因为用户可以有超过 1 笔存款
    • 从你说的情况来看,users表中有89行状态为1。这就是你想要得到的结果吗?
    【解决方案2】:

    在您的第一个查询中,您没有取回所有行的原因是因为您按deposits.user_id 分组,这不会对所有用户都存在。

    ->groupBy('deposits.user_id')
    

    您应该按users.id 分组

    在您的第二个查询中,您没有在左表中获取所有行的原因是因为您在 where 子句中引用了右表 deposits,这意味着任何时候都没有匹配在 deposits 上,这些值将为 null 并且您的 where 失败。

    解决方案是将depositswhere 条件移动到您的left join

    leftJoin('deposits', function($join) {
        $join->on('deposits.user_id', '=', 'users.id')
             ->on('deposits.status','=',DB::raw("'completed'"))
             ->on('deposits.created_at', '>=',  \Carbon\Carbon::now()->subDays(25);
    })
    

    【讨论】:

    • 我仍然收到错误消息。这个stackover flow评论markdown非常有限。你可以在这里看到错误gist.github.com/najela/802f9620f5b68865acae
    • @bePolite 查看更新,您需要使用DB::raw 所以completed 被解释为字符串而不是列
    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多