Inner Join table on 1 = 1 can be considered a gambiarra?

Asked

Viewed 458 times

1

I have a table of provas and a table of alunos who have no direct relationship, I still have a table of inscrição aluno and a table of escolas, as follows in the modeling below:

DER

I need to create a select to bring how many students from each school are enrolled in each test.

I resorted to a gambiarra with great reservations because the SELECT worked perfectly:

SELECT (SELECT count(ia.idaluno) FROM inscricaoaluno ia INNER JOIN alunos a ON a.idaluno = ia.idaluno
WHERE a.idpessoa_juridica = e.idpessoa_juridica AND ia.idprova = p.idprova) qtd, e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
FROM escolas e
INNER JOIN prova p ON 1 = 1 
GROUP BY e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
ORDER BY e.nome;

"I created a nonexistent relationship" of the school table with the proof table using a INNER JOIN ON 1 = 1, with this I listed all the tests for each school, if I have the following data for example:

inserir a descrição da imagem aqui

This "nonexistent" relationship will bring me the following result:

inserir a descrição da imagem aqui

With that I create a subquery in the data that brings me the amount of each student in each test according to the school that he studies.

Now comes that doubt, is that a gambit? The result is satisfactory, it works, but many people do not look kindly on the use of 1 = 1

1 answer

4


Yes, it is a trick. The correct thing in this case would be to apply a CROSS JOIN

SELECT (SELECT count(ia.idaluno) FROM inscricaoaluno ia INNER JOIN alunos a ON a.idaluno = ia.idaluno
WHERE a.idpessoa_juridica = e.idpessoa_juridica AND ia.idprova = p.idprova) qtd, e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
FROM escolas e
CROSS JOIN prova p
GROUP BY e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
ORDER BY e.nome;

An alternative syntax may be:

SELECT (SELECT count(ia.idaluno) FROM inscricaoaluno ia INNER JOIN alunos a ON a.idaluno = ia.idaluno
WHERE a.idpessoa_juridica = e.idpessoa_juridica AND ia.idprova = p.idprova) qtd, e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
FROM escolas e, prova p
GROUP BY e.nome, e.idpessoa_juridica , p.descprova, p.idprova  
ORDER BY e.nome;
  • @Marcelo, only now I saw that it is for Oracle. You can confirm the syntax of the last query (comma instead of CROSS JOIN)?

  • Yes, both of you selects perform in the same way, did not know this relationship of type cross, but from what I see it’s the same thing I put the two after the from correct?

  • That’s right. I prefer the first way because it is clearer what is happening in the query. A comma is easy to go unnoticed, but a CROSS JOIN nay =)

  • 1

    Regarding performance, in tests that I did here in my environment, the three forms have practically the same performance

Browser other questions tagged

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