SQL query does not return expected items

Asked

Viewed 47 times

1

I have two tables called Protocol and Analyze with a 1:n relationship, a Protocol may have several Analysis, Protocol has a composite primary key. I need to write an SQL that returns the Protocols that have no Analysis and the Protocols that have at least one Analysis. I tried to write some, but without success, the queries do not return the expected items, or return nothing

|PROTOCOLO      |         |ANALISE              |
|prefixo PK     |         |idanalise PK         |
|numero  PK     |         |prefixo FK           |
|ano     PK     |         |numero  FK           |
|// OUTROS ATTRS|         |ano     FK           |
                          |// OUTROS ATRIBUTOS  |

SQL I tried to do for Protocols without any analysis

SELECT * FROM protocolo p WHERE p.prefixo 
NOT IN (SELECT a.protocolo_prefixo 
FROM analise a) 
AND p.numero NOT IN (SELECT a.protocolo_numero 
FROM analise a) 
AND p.ano NOT IN (SELECT a.protocolo_ano 
FROM analise a)

SQL I tried to do for protocols with at least 1 parsing

SELECT * FROM protocolo p WHERE p.prefixo 
IN (SELECT a.protocolo_prefixo 
FROM analise a) 
AND p.numero IN (SELECT a.protocolo_numero 
FROM analise a) 
AND p.ano IN (SELECT a.protocolo_ano 
FROM analise a)
  • 1

    I made an online example to use base to solve the problem: http://sqlfiddle.com/#! 17/bbabe/13

  • @David, thanks for your help.

1 answer

3


Protocols without any analysis:

SELECT * FROM protocolo WHERE NOT EXISTS (SELECT 1 FROM analise WHERE protocolo.prefixo = analise.prefixo AND protocolo.numero = analise.numero AND protocolo.ano = analise.ano);

or:

SELECT protocolo.* FROM protocolo LEFT OUTER JOIN analise ON (protocolo.prefixo = analise.prefixo AND protocolo.numero = analise.numero AND protocolo.ano = analise.ano) WHERE analise.prefixo IS NULL;

To know which protocols have at least one analysis just do an INNER JOIN:

SELECT protocolo.* FROM protocolo INNER JOIN analise ON (protocolo.prefixo = analise.prefixo AND protocolo.numero = analise.numero AND protocolo.ano = analise.ano);

Now in your queries you do not use the table analyze to which you refer at the beginning of your question.

  • Actually, I was going through some things here and I got confused with the name of the tables when writing the query here, I already edited the question

  • I took the test here and it worked, thank you!

  • can you answer my question? https://answall.com/questions/469237/identificar-registrations-sequentialof each user

Browser other questions tagged

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