mysql - 子查询中不存在的地方

标签 mysql database laravel eloquent subquery

我想要实现的目标如下:

我想检查是否存在具有相同 client_code 但具有较低/不同 campaign id 的记录。我现在使用子查询,我也尝试使用连接来完成它,但我无法让逻辑工作

这就是我现在得到的:

    $oDB = DB::table('campaigns AS c')
        ->select(
            'c.id AS campaign_id',
            'cc.id AS campaign_customer_id'
        )
        ->join('campaign_customers AS cc', 'cc.campaign_id', '=', 'c.id')
        ->where('c.status', '=', ModelCampaign::STATUS_PLANNED)
        ->where('c.scheduled', '=', 1)
        ->whereRaw('c.scheduled_at <= NOW()')
        ->where('cc.status', '=', ModelCampaignCustomer::STATUS_INVITE_EMAIL_SCHEDULED)
        ->whereNotIn('cc.client_code', '=', function ($query){
            $query  ->select(DB::raw(1))
                    ->from('campaign_customers')
                    ->whereRaw('campaign_id', '!=', 'c.id');
        })
        ->where('cc.active', '=', 1)
    ;

任何关于如何运作逻辑的提示都会很棒

最佳答案

您可以使用 ->to Sql(); 方法查看 SQL,以便重构您的查询。

关于mysql - 子查询中不存在的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38699492/

相关文章:

当添加尾部斜杠时,Laravel 恢复为/public/in URL

laravel - 从 Illuminate\Html 切换到 Collective\Html,未找到类 'Illuminate\Html\HtmlServiceProvider'

php - 基于下拉选择的SQL查询

php - 在Mysql中查找记录的查询

MySQL 事务 : multiple concurrent transactions and data integrity

mysql - 如果绑定(bind)字段为空,如何使用左连接发出请求 |数据库

mysql - 一般错误 : 1005 Can't create table

php - MySql查询2条记录为1条结果

MySQL 同一列的不同条件

ruby-on-rails - Ruby on Rails 多态关系的优点和缺点