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

时间:2017-06-25 04:04:52

标签: mysql laravel eloquent

我有这个查询,我在laravel eloquent ORM中编写查询时遇到了麻烦。

感谢有人可以提供帮助。

这是SQL Expression:

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)

4 个答案:

答案 0 :(得分:9)

您可以像下面显示的那样使用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`)

答案 1 :(得分:6)

尝试这样的事情:

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

答案 2 :(得分:0)

我更正了下面的代码('cust')以采取('cust_name')和 pluck('cust_no')to 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();

答案 3 :(得分:0)

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

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
)

OR

SELECT DISTINCT d.cust, d.cust_no 
FROM delivery_sap d
LEFT JOIN delivery_sap d1 ON d.cust = d1.cust_name OR d.cust = d1.cust_code 
WHERE d1.cust IS NULL

DB::table('delivery_sap as d')
    ->leftJoin('delivery_sap as d1', function ($join) {
        $join->on('d.cust','=','d1.cust_name')
             ->orWhere('d.cust', '=', 'd1.cust_code');
   })
    ->whereNull('d1.cust')
    ->select('cust', 'cust_no')
    ->distinct()
    ->get();