Mysql 拉雷维尔雄辩地用两个“;不在”;在子查询中

Mysql 拉雷维尔雄辩地用两个“;不在”;在子查询中,mysql,laravel,eloquent,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) 试着这样做: DB::table('delivery_sap')

我有一个问题,我很难用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)

试着这样做:

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();

我将下面的代码pull('cust')更正为pull('cust_name'),并且 pull('cust_no')到pull('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();

您可以使用
exists
left
连接以获得更好的性能,而不是像现有解决方案那样在同一个表上使用子查询,不需要这两个额外的子查询

SELECT DISTINCT cust, cust_no 
FROM delivery_sap d
WHERE EXISTS (
    SELECT 1
    FROM delivery_sap
    WHERE cust_name = d.cust OR cust_code = d.cust
)


而不是执行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();
该代码将给出与问题中所问完全相同的查询, 要检查查询,请使用以下代码

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();
产量将是,

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`)

我已经更新并尝试了新的答案,找到了一个不起作用的好答案。我正试图找出原因。about在phpmyadmin中起作用,但我的it显示“字段列表中的未知列'cust'”。在customer表中,您有不同的列名。如果您的问题已经解决,请关闭问题。这会得到所需的数据,但与问题所问的不完全相同。它执行3个单独的查询。请参阅下面Akshay Kulkarni的答案,了解如何使用advanced Where在单个查询中完成此操作
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`)