Problem in Mysql query

Asked

Viewed 85 times

4

I’m having a problem with a Mysql query. In it I have 3 tables I need to cross:

Table "drawing":

id
concurso_id
customer_id

Table "competition":

id 
titulo   
criterioDiasCorridos
criterioNotaMedia
criterioMinimoVotos

Table "noteworthy":

customer_id
desenho_id
concurso_id
nota

It is a voting system where I need to list all the DRAWINGS of THE CONTEST X (contest.id = X) and ADD amount of votes that the drawing had (noteworthy.drawing.drawing.id) and display the AVERAGE of votes also (noteworthy.note).

I made the following consultation:

SELECT
    d.id,
    d.nome,
    d.descricao,
    d.arquivo,
    d.tags,
    d.concurso_id,
    c.criterioNotaMedia,
    c.criterioMinimoVotos,
    c.criterioDiasCorridos,
    COUNT(n.desenho_id) as quantidadeVotos,
    IFNULL(AVG(n.nota), 0) as notaDesenho
FROM desenho d
LEFT JOIN concurso c ON d.concurso_id = c.id 
LEFT JOIN notadesenho n ON d.id = n.desenho_id
WHERE c.id = $idConcurso

But it is returning only 1 drawing when I ask to list all from the X contest.

I suspect the problem is in the JOIN links. But I’m not being able to see the solution.

  • Felipe, if you can, create a MCVE with your schema and a sample of the data in an online SQL debugging tool (p.e: Sqlfiddle). Makes it easier to visualize the problem and discover the solution.

  • For me it’s clear enough.

1 answer

3


The problem in your query is in COUNT() and in the AVG().

They are aggregated functions and should be used together with GROUP BY to produce the expected result.

Your query should look something like this (Grouping the drawings by id):

SELECT
    d.id,
    d.nome,
    d.descricao,
    d.arquivo,
    d.tags,
    d.concurso_id,
    c.criterioNotaMedia,
    c.criterioMinimoVotos,
    c.criterioDiasCorridos,
    COUNT(n.desenho_id) as quantidadeVotos,
    IFNULL(AVG(n.nota), 0) as notaDesenho
FROM desenho d
LEFT JOIN concurso c ON d.concurso_id = c.id 
LEFT JOIN notadesenho n ON d.id = n.desenho_id
WHERE c.id = $idConcurso
GROUP BY d.id
  • Thank you very much! It worked perfectly!

  • just one question, is there an order to put "Group by" in the whole query? Does it have to go underneath everything? Because my question is: Can I use Group By and Order By with the same field? GROUP BY d.id ORDER BY d.id $order

  • 1

    @Felipe order by always at the end of the query. To understand a little about how querys are executed, see this answer (in English) http://dba.stackexchange.com/questions/72022/mysql-select-using-alias/72023#72023

Browser other questions tagged

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