Compare id of two tables and insert value when id does not exist

Asked

Viewed 31 times

0

Hello, I’m comparing two tables that have the same data, tabela1 and tabela2, to tabela2 will have data deleted over time, and so need to identify the field that was deleted and insert an "delete status" in a column of the tabela1.

I’ll try to explain it this way:

+---------+---------+----------+
| TABELA2 | TABELA1 |          |
+---------+---------+----------+
| cod1    | cod1    |          |
+---------+---------+----------+
|         | cod2    | EXCLUIDO |
+---------+---------+----------+
| cod3    | cod3    |          |
+---------+---------+----------+
|         | cod4    | EXCLUIDO |
+---------+---------+----------+

Code I already have, it already performs the comparison but does not include the status of "deleted":

$teste1 = "SELECT * FROM tabela2 as a INNER JOIN tabela1 as c ON (a.cod2=c.cod1)";
    $teste2 = mysqli_query ($db,$teste1);
    while($teste3 = mysqli_fetch_array($teste2)){
        $teste = $teste3["0"];

        $insert = "UPDATE tabela1 SET campo = 'Entregue' WHERE cod1 NOT IN ($teste)";
        mysqli_query ($db,$insert);
    }

1 answer

0


Hello you can run the query below to know who was deleted:

select * from tabela1 t1  where not exists(select * from tabela2 t2 where t2.id = t1.id )

And to update the status you can run only the command below:

update tabela1 t1 set t1.status = "EXCLUIDO" where not exists(select * from tabela2 t2 where t2.id = t1.id )

See the examples here http://sqlfiddle.com/#! 9/eb5a21/3

  • Thank you very much!! It worked perfectly, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.