compare sql tables displaying different result

0

I have a sql query that lists two tables:

Register and release.

I have an application that adds the "id" of "register" in the "release" table, I want to display only the results that do NOT exist in the "unpin" table.

follow the query:

$verifica = $db->prepare("SELECT liberar.aluno AS alunoID, liberar.title, cadastro.nome AS name, cadastro.id AS idAluno FROM cadastro INNER JOIN liberar ON (cadastro.id = liberar.aluno) WHERE liberar.title = ? GROUP BY cadastro.nome ORDER BY cadastro.nome");
    $verifica->execute(array($identificador));

This $ identifier variable is the title that I get for GET. this query returns me the ids that were added in releasing, however I want to return the ones that are not added only.

I have tried to change (cadastro.id! = release.aluno) but so it returns me all the id, I need to return only the ids that were sent to release ..

    
asked by anonymous 26.10.2018 / 17:31

3 answers

1

The query below returns all records that are not registered in the release table:

SELECT
    cadastro.id
 FROM
     cadastro
 WHERE
       NOT EXISTS ( SELECT * FROM liberar where liberar.aluno =  cadastro.id )
 GROUP BY
     cadastro.nome
 ORDER BY
     cadastro.nome

However you can not filter by the release.title because the title exists only in the release table, and in the records you want there are no items in the release tables.

    
26.10.2018 / 18:06
0

I'll put two examples where I want customers who do not have sales

1 - 

SELECT DISTINCT.* FROM CLIENTES C
LEFT JOIN VENDAS V ON(V.CODID = C.CODID)
WHERE (V.CODID IS NULL)

2 - 

SELECT DISTINCT C.* FROM CLIENTES
WHERE (CODID NOT IN(SELECT CODID FROM VENDAS))

Both of them bring the same result, what changes is the performance depending on the amount of records in each table

Assuming that the CLIENTS table is huge, the first example will be slower, if SALES is the second example will be slower

You should take into account the appropriate indexes created in each table and the additional filters in the WHERE clause

    
26.10.2018 / 17:51
0

Solved with the tip of Marciano Machado, thank you!

  

NOT EXISTS (SELECT * FROM release WHERE student = cadastro.id)

"SELECT cadastro.*, liberar.* FROM cadastro INNER JOIN liberar WHERE liberar.title = ? AND NOT EXISTS (SELECT * FROM liberar WHERE aluno =  cadastro.id ) GROUP BY cadastro.nome ORDER BY cadastro.nome"
$verifica->execute(array($identificador));

I have adapted this way: includes the join of the tables to retrieve the title because it is the title that I retrieve by the $ identifier variable in the GET, this variable filters the query by title, since the application will have titles based on school subjects.     

26.10.2018 / 18:37