5

I have a problem in counting by MySQL in a GROUP BY This is the query that does not return the desired result.

SELECT COUNT(bagno)
FROM disposizione_assegnazione_pezze
JOIN pezze 
  ON pezza = id
WHERE id_prodotto_tessuto = 12096
  AND id_collezione = 11 
  AND id_stagione = 22 
  AND id_tema = 1
GROUP BY bagno

The result of the count is 3

This is the pezza table and its primary key is id

Table pezza with results

This is the table disposizione_assegnazione_pezze that has the pezza column which refers to the previous table

Table disposizione_assegnazione_pezze

Why does not return 1 as a result my query?


Question of the problem

I want to count how many different bagno are there

Lorenzo Belfanti
  • 1,205
  • 3
  • 25
  • 51

1 Answers1

11

I dont think you need GROUP BY, instead use DISTINCT

 SELECT COUNT(DISTINCT bagno)

SQL DEMO

Check your query without agregatted function COUNT/GROUP BY

enter image description here

As you can see bagno = 55 appear three times, that is why when you group by bagno and count get 3.

Juan Carlos Oropeza
  • 47,252
  • 12
  • 78
  • 118
  • So it works, but I do not understand why. If I use the `GROUP BY` I group all results to have them different, in my case it will return only one result, so if you should count with `COUNT` function I think should be corrected. – Lorenzo Belfanti Dec 13 '16 at 14:28
  • Maybe if you explain what are those fields, or put a bigger example I can give you more detail. – Juan Carlos Oropeza Dec 13 '16 at 14:31
  • 1
    Check my edit explanation. That is exactly what `DISTINCT` does – Juan Carlos Oropeza Dec 13 '16 at 14:37
  • Works great, however, Why if I make a `GROUP BY` and `SELECT *` result only one line? Taking a `COUNT (*)` should not return **1** as a result? Example: http://rextester.com/KNOBO9612 – Lorenzo Belfanti Dec 13 '16 at 14:41
  • Samething, the only difference is `COUNT(*)` count the number of row not matter what values are there, `COUNT(bagno)` only count rows where `bagno IS NOT NULL` so ignore null rows. – Juan Carlos Oropeza Dec 13 '16 at 14:43