Query to not repeat an already registered value

Asked

Viewed 74 times

1

I have the following situation:

I need to make an SQL query in a field to return only the vehicles that are registered in a form (table vehicles) and that the form despachos_ocorrencias the vehicles that have already been "chosen" do not appear in the vehicle field of this form. But they are all appearing, I can not for example, make this mine SELECT ignore the vehicle that was already chosen in the form despacho_ocorrencias (table despacho_ocorrencias).

For example, I have the vehicle 24, 56, 50 e 70 registered in the form of vehicles, I have the vehicle 24 already chosen (registration registered in the table of despacho_ocorrencias), when I register a new registration in the form appear all vehicles 24, 56, 50 and 70 instead of appearing only 56, 50 and 70. I wish 24 didn’t show up because she’s already chosen for one despacho_ocorrencia.

I made my SQL like this.

Select distinct viaturas.vtr_numero
  From viaturas, despacho_ocorrencias
 Where despacho_ocorrencias.vtr_atendimento = viaturas.vtr_numero and 
       viaturas.parado_manutencao=‘NÃO’ and 
       viaturas.parado_utilizacao=‘NÃO’ and 
       despacho_ocorrencias.fechar_despacho!=“1”

Note: this "1" is a closed dispatch flag.

Any suggestions?

  • It would be better if you gave a practical example with input data and output data, preferably using a fiddle, as a DB Fiddle.

1 answer

0

From what I understand you want those vehicle numbers that exist in vehicles but are not registered in dispatch_occurrences. Try:

Select distinct viaturas.vtr_numero
  From viaturas
 Where NOT EXISTS(SELECT * FROM despacho_ocorrencias WHERE despacho_ocorrencias.vtr_atendimento = viaturas.vtr_numero) and 
       viaturas.parado_manutencao=‘NÃO’ and 
       viaturas.parado_utilizacao=‘NÃO’ and 
       despacho_ocorrencias.fechar_despacho!=“1”

Browser other questions tagged

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