Select different values in two tables - SQL and PHP

Asked

Viewed 1,885 times

0

I have two tables to pedido_tb and the pedido_grade, what I want to do is compare, the values of the column "request" of the requested table and column "n_pedido" of pedido_grade, basically, would like to get the values you have in pedido_tb and do not have in pedido_grade.

I tried the following code:

$sql = "SELECT pedido FROM pedido_tb WHERE pedido NOT IN (SELECT n_pedido FROM pedido_grade)";

$disp_sql = $mysqli->query($sql);

$num = $disp_sql->num_rows;

echo "</br>número de linhas ".$num."</br>";

Does anyone have any idea why nothing returns?

  • The query is apparently correct. I answered your question using LEFT JOIN, if it doesn’t work check if your php errors are not disabled, there may be some connection error or pointing to a wrong base. has n possibilities.

3 answers

2

SELECT pedido FROM table1 WHERE pedido NOT IN (SELECT n_pedido FROM table2)
  • Hello Rodrigo, I edited my question because the code did not work :/

2

Just make a simple SELECT with subquery

SELECT pedido FROM table1 WHERE pedido NOT IN (SELECT n_pedido FROM table2)

However, if you need one day to display records of the two tables you can use JOIN, so I’ll leave you an example to study

INNER JOIN

SELECT pedido.table, n_pedido.table2 FROM table1
    INNER JOIN table2 ON table1.id = table2.id

LEFT OUTER JOIN

SELECT pedido.table, n_pedido.table2 FROM table1
     LEFT OUTER JOIN table2 ON table1.id = table2.id
  • thanks for replying @Victor, I saw that in your comparison table1.id = table2.id, the two columns have the same name, and if they are of different names, also employee? thank you

  • i gave an example to you that the comparison is the id, so the two tables have to have the id column, but if you indicate for example, imagine that table 1 has a product field and table 2 has an id_product field so, table1.product = table2.id_product will work in this case

0

Make a query with LEFT JOIN and do 1 WHERE the column of the table on the left is null, then return only the requests that have no grid request:

SELECT
    p.*
FROM pedido p
LEFT JOIN pedido_grade pg
ON p.pedido = pg.n_pedido
WHERE pg.n_pedido IS NULL;

Browser other questions tagged

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