Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

281
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda