How to join two tables and select non matching columns

Viewed 391

I'm trying to write a laravel SQL query to join two tables and extract the non-matching columns from tables.

Products Table

id Name
1 abe
2 edfg
3 swfgd
4 df
5 fg

Clearing Table

Product_id Name
2 edfg
4 df
5 fg

Now, I'm expecting the result table to be the following.

Result table

id Name
1 abe
3 swfgd

Can anyone help me with this?

3 Answers

We can try using a left anti-join approach here:

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

This would correspond to the following SQL query:

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;

I would suggest you to create model for each table.

For Products table create model using command

php artisan make:model Product

This command will create file in app/Models and add relationship 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');
    }
}

and same way create model for 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";
}

and in your controller

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

You can use not exists:

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