繁体   English   中英

如何连接两个表并选择不匹配的列

[英]How to join two tables and select non matching columns

我正在尝试编写一个 Laravel SQL 查询来连接两个表并从表中提取不匹配的列。

产品表

ID 名称
1 阿部
2 edfg
3 swfgd
4 df
5 fg

清理表

产品编号 名称
2 edfg
4 df
5 fg

现在,我期待结果表如下。

结果表

ID 名称
1 阿部
3 swfgd

谁能帮我这个?

我们可以在这里尝试使用左反连接方法:

$users = DB::table('Products p')
    ->select("p.id", "p.Name")
    ->leftJoin('Clearings c', function($join) {
        $join->on('p.id', '=', 'c.Product_id');
        $join->on('p.Name', '=', 'c.Name');
    })
    ->whereNull('c.Product_id');
    ->get();

这将对应于以下 SQL 查询:

SELECT p.*
FROM Products p
LEFT JOIN Clearing c
    ON p.id = c.Product_id AND p.Name = c.Name
WHERE
    c.Product_id IS NULL;

我建议您为每个表创建模型。

对于产品表使用命令创建模型

php artisan make:model Product

此命令将在app/Models创建文件并添加关系hasMany

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $table="Products";

    public function clearing(){

        return $this->hasMany(Clearing::class,'Product_id','id');
    }
}

并以同样的方式为 Clearing table 创建模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Clearing extends Model
{
    use HasFactory;

    protected $table="Clearing";
}

并在您的控制器中

$products=Product::whereDoesntHave('clearing')->get()

您可以使用not exists

select p.*
from products p
where not exists (select 1 from clearing c where c.product_id = p.id);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM