Query with 3 conditions AND does not work the last condition

Asked

Viewed 110 times

1

I would like to make a query in two tables that takes into account 3 criteria, but is not presenting the expected result.

Select viaturas.vtr_numero
From viaturas, despacho_ocorrencias
Where 
viaturas.parado_manutencao='NÃO' and 
viaturas.parado_utilizacao='NÃO' and
despacho_ocorrencias.fechar_despacho='NÃO'
group by viaturas.vtr_numero

In this query above I would like to show only the number of vehicles that had no maintenance, that had no use stops and with open dispatch (in this case with flag 'YES')but the last condition is not working because the ones with flag 'YES' and 'NO'.

Is there something wrong in the query? if I do the first two conditions is normal, put together the last condition the result does not match.

  • can show how are the data in the table? it was not very clear

  • Marcelo would be the ideal you put the table structure and an example of the expected output, so it would be easier to help you

  • 1

    Xará, what is the relationship between the tables viaturas and despacho_ocorrencias? You’re making a Cartesian product from both tables.

  • as @Marceloshinitiuchimura commented, is using two tables without establishing the relationship between them (with join or in the where), then do the cartesiado, combining the results

  • I do not understand why this clause GROUP BY if you do not use any aggregation function. Assuming that when you say "with open dispatch (in this case with flag 'YES')" you are referring to another field other than the dispatch_occurrences.close_dispatch specified in the query then you would only have to replace it with the correct field. Note that you are making a CROSS JOIN, or Cartesian product of the vehicle tables and dispatch_occurrences.

  • By the comments are missing link the two tables, I will make test.

Show 1 more comment

1 answer

1


We had to adjust the join.

You are giving select in two tables without "linking" the same.

Enter a condition viaturas.CampoRelacionado = despacho_ocorrencias.CampoRelacionado to avoid a select of the combination of these.

As they said in the comments, is not making sense the group by since there is no aggregation in the query.

  • Really missing link the two tables, I will do test. thank you

Browser other questions tagged

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