mysql – count with LEFT JOIN does not return when zero or null

Question:

I'm having a problem in a select where I need to get the data from 3 tables (research, users, and answer_pesquisa). Where poll_response may or may not 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

Data from pc_pesquisa and users tables return ok, but it only returns searches that have responses recorded. And I need to return even when there isn't (null or zero).

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

Answer:

I managed to solve the problem, apparently I needed to group the results. The query looked 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 responses. I don't know why, but it works haha. So you can close this question once the problem has been resolved.

Scroll to Top