Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

280
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda