Count with LEFT JOIN does not return when zero or null

Asked

Viewed 401 times

3

I have a problem in a select where I need to get the data from 3 tables (search, users, and search). Where query can or n have data. The current query is:

SELECT 
usuarios.nome AS nome_autor,
pc_pesquisa.*,
COUNT(pc_resposta_pesquisa.id) AS respostas 
FROM pc_pesquisa
    LEFT JOIN usuarios
        ON usuarios.id = pc_pesquisa.id_autor
    LEFT JOIN pc_resposta_pesquisa
        ON pc_resposta_pesquisa.id_pesquisa = pc_pesquisa.id
WHERE pc_pesquisa.id_tipo = 1 ORDER BY pc_pesquisa.data ASC

The data from the pc_search tables and users return ok, but only returns the searches that have registered answers. And I need to return even if there is no (null or zero).

Currently I have 2 registered searches, one with 4 answers and the other with 0 answers. This query only returns the survey that has answers.

1 answer

0


I managed to solve the problem, apparently I needed to group the results. The query was like this:

SELECT 
usuarios.nome AS nome_autor,
pc_pesquisa.*,
COUNT(pc_resposta_pesquisa.id) AS respostas 
FROM pc_pesquisa
    LEFT JOIN usuarios
        ON usuarios.id = pc_pesquisa.id_autor
    LEFT JOIN pc_resposta_pesquisa
        ON pc_resposta_pesquisa.id_pesquisa = pc_pesquisa.id
WHERE pc_pesquisa.id_tipo = 1 
    GROUP BY pc_pesquisa.id 
    ORDER BY pc_pesquisa.data ASC

This way it returns even when there are 0 answers. N know pq, but it works haha. So you can close this question since the problem has been solved.

  • Whenever aggregation functions are used in a query it is necessary to specify an aggregation. By default Mysql does not do this validation but does not guarantee that the answer is right.

Browser other questions tagged

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