Laravel Eloquent在子查询中带有两个“ WHERE NOT IN”

Wah*_*sei 9 mysql laravel eloquent

我有这个查询,我很难在Laravel雄辩的ORM中编写查询。

感谢有人可以提供帮助。

这是SQL表达式:

SELECT DISTINCT cust, cust_no FROM delivery_sap 
WHERE cust NOT IN ( SELECT cust_name FROM customer) 
AND cust_no NOT IN ( SELECT cust_code FROM customer)
Run Code Online (Sandbox Code Playgroud)

Aks*_*rni 12

无需执行3个不同的查询,您可以使用如下所示的方法,

DB::table('delivery_sap')
->whereNotIn('cust', function ($query) {
        $query->select('cust_name')->from('customer');
    })
->whereNotIn('cust_no', function ($query) {
        $query->select('cust_code')->from('customer');
    })
->select('cust', 'cust_no')
->distinct('cust')
->get();
Run Code Online (Sandbox Code Playgroud)

该代码将给出与问题完全相同的查询,以检查查询,使用以下代码

DB::table('delivery_sap')
->whereNotIn('cust', function ($query) {
        $query->select('cust_name')->from('customer');
    })
->whereNotIn('cust_no', function ($query) {
        $query->select('cust_code')->from('customer');
    })
->select('cust', 'cust_no')
->distinct('cust')
->toSql();
Run Code Online (Sandbox Code Playgroud)

输出将是

select distinct `cust`, `cust_no` from `delivery_sap` 
where `cust` not in (select `cust_name` from `customer`) 
and `cust_no` not in (select `cust_code` from `customer`)
Run Code Online (Sandbox Code Playgroud)


Sag*_*tam 7

尝试这样的事情:

DB::table('delivery_sap')
    ->whereNotIn('cust', DB::table('customer')->pluck('cust'))
    ->whereNotIn('cust_no', DB::table('customer')->pluck('cust_no'))
    ->select('cust', 'cust_no')
    ->groupBy('cust', 'cust_no')
    ->get();
Run Code Online (Sandbox Code Playgroud)

  • 这将获得所需的数据,但与问题的要求不完全相同。它执行3个独立的查询。请参阅下面的Akshay Kulkarni的答案,以了解如何使用高级wheres在单个查询中执行此操作 (2认同)

Wah*_*sei 3

我将下面的代码更正为 pluck('cust') 为 pluck('cust_name') 和 pluck('cust_no') 为 pluck('cust_code') 并且它有效

DB::table('delivery_sap')
    ->whereNotIn('cust', DB::table('customer')->pluck('cust_name'))
    ->whereNotIn('cust_no', DB::table('customer')->pluck('cust_code'))
    ->select('cust', 'cust_no')
    ->groupBy('cust', 'cust_no')
    ->get();
Run Code Online (Sandbox Code Playgroud)