Im struggling with two apparently easy queries.
Query n1 (WORKS):
SELECT
cliente.*,
COUNT(*) AS 'num_installazioni',
CONCAT(provincia.nome, ' (', provincia.sigla, ')') AS 'provincia'
FROM q_cliente AS cliente
JOIN dettaglio_installazione AS dettinst ON cliente.id = dettinst.cliente
JOIN q_sede AS sede ON sede.id_cliente = cliente.id
JOIN quadra_provincia_table AS provincia ON provincia.id = sede.id_provincia
WHERE 1 = 1 AND 'num_installazioni' < 5
GROUP BY cliente.id;
Query n2 (DOESN'T WORK):
SELECT
cliente.*,
CONCAT(provincia.nome, ' (', provincia.sigla, ')') AS 'provincia',
COUNT(*) AS 'num_pulizie'
FROM q_cliente AS cliente
JOIN q_sede AS sede ON sede.id_cliente = cliente.id
JOIN quadra_provincia_table AS provincia ON provincia.id = sede.id_provincia
JOIN quadra_attivita AS att ON cliente.id = att.id_cliente
WHERE 1 = 1 AND 'num_pulizie' >= 5 AND 'num_pulizie' <= 10
GROUP BY cliente.id;
Query n2 (WORKING VERSION):
SELECT
cliente.*,
COUNT(*) AS `pulizie`,
CONCAT(provincia.nome, ' (', provincia.sigla, ')') AS 'provincia'
FROM q_cliente AS cliente
JOIN q_sede AS sede ON sede.id_cliente = cliente.id
JOIN quadra_provincia_table AS provincia ON provincia.id = sede.id_provincia
JOIN quadra_attivita AS att ON cliente.id = att.id_cliente
GROUP BY cliente.id
HAVING `pulizie` >= 5 AND `pulizie` <= 10;
Context:
I can't really figure out why the first one works, according to some other answers i've found here on stackoverflow:
- Using column alias in WHERE clause of MySQL query produces an error
- Why can't I use alias in a count(*) "column" and reference it in a having clause?
I should have used COUNT(*) alias in HAVING clause according to those answers, and in fact it works (see 3rd query) but the fun fact is that query n1 is VERY similar and yet it works. What I'm sure it changes is the number of rows of the joining table to which I'm counting over (one has over 4k rows (query n2), the other one has less then 100 (query n1).
In addition to that query n2 (working version) uses ` while query n1 (working) uses '. I'm so confused...
Can someone please explain me what I'm doing (or thinking) wrong?