【问题标题】:Compare same column in different tables Laravel比较不同表中的同一列 Laravel
【发布时间】:2021-03-26 19:35:15
【问题描述】:

我有 2 个表,我正在尝试匹配记录并输出不匹配的记录。

  • 表 A 是一个生产表,其中包含 nameupc。 (有模型)

  • 表 B 是一个导入的 Excel 表,其中包含 nameupc(无模型,只有表)

  • 表 A 有 986 行

  • 表 B 有 991 行

主要目标是从表 B 中获取缺失的行并将它们添加到 表 A。

我还想获得以下信息:

  1. 表 A 和表 B 中匹配 upc 的数量
  2. 表 A 和表 B 中不匹配 upc 的数量
  3. 输出不匹配的name & upc

我将如何实现这一目标?

对于 #1 我试过了:

use \App\Models\A;

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

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

这会输出 990 的计数,这是没有意义的,因为表 A 只有 986 行。

我知道我可能比现在更难做到这一点。 任何帮助或正确方向的观点将不胜感激。

【问题讨论】:

  • 也许这4条额外的记录是被骗的upcs?
  • 啊,好电话。我没想到。

标签: php mysql database laravel eloquent


【解决方案1】:

你可以使用Where Exists Clauses

whereExists 方法允许您编写“where exists”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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-08-27
    • 2017-02-14
    • 2014-03-23
    • 1970-01-01
    • 2015-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多