Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
How to join two tables and select non matching columns

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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report

0

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()
over 4 years ago · Santiago Trujillo Report

0

You can use not exists:

select p.*
from products p
where not exists (select 1 from clearing c where c.product_id = p.id);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!