簡體   English   中英

比較不同表中的同一列 Laravel

[英]Compare same column in different tables Laravel

我有 2 個表,我試圖匹配記錄和 output 不匹配的記錄。

  • 表 A 是包含name upc的生產表。 (有模型)

  • 表 B 是一個進口的 Excel 表,包含nameupc (沒有 Model,只有表)

  • 表 A 有 986 行

  • 表 B 有 991 行

主要目標是從表 B 中獲取缺失的行並將它們添加到表 A。

我還想獲得以下信息:

  1. 表 A 和表 B 中匹配的upc數量
  2. 表 A 和表 B 中不匹配的upc數量
  3. Output 不匹配的nameupc

我將如何實現這一目標?

對於#1,我嘗試過:

use \App\Models\A;

$matchingUpc = A::join('b', 'b.upc', '=', 'a.upc')->count();

dd($matchingUpc); // = 990 ???

這會輸出 990 的計數,這是沒有意義的,因為表 A 只有 986 行。

我知道我可能比現在更難做到這一點。 任何幫助或正確方向的觀點將不勝感激。

你可以使用Where Exists 子句

whereExists 方法允許您編寫“在哪里存在”SQL 子句。 whereExists 方法接受一個閉包,該閉包將接收一個查詢構建器實例,允許您定義應該放在“exists”子句中的查詢:

 $upcMatching  = DB::table('production')
            ->whereExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('imported')
                    ->whereColumn('production.upc', 'imported.upc');
            })->count();
      

        $upcNotMatching = DB::table('production')
            ->whereNotExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('imported')
                    ->whereColumn('production.upc', 'imported.upc');
            })->get();


 $numberOfUnMatchedCount=DB::table('production')->count('upc')-$upcMatching;

//or simply:

$numberOfUnMatchedCount= $upcNotMatching->count();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM