Mysql:算作别名

时间:2017-06-16 10:09:03

标签: mysql having

我正在努力解决两个看似简单的问题。

查询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;

查询n2(不工作):

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;

查询n2(工作版):

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;

上下文:

根据我在stackoverflow上找到的其他答案,我无法弄清楚为什么第一个有效:

我应该根据这些答案在HAVING子句中使用COUNT(*)别名,实际上它可以工作(参见第3个查询),但有趣的事实是查询n1非常相似但却有效。 我确定它改变的是我正在计算的连接表的行数(一个有超过4k行(查询n2),另一个有少于100(查询n1)。

除了那个查询之外,n2(工作版)使用`while query n1(working)使用'。我很困惑......

有人可以解释一下我在做什么(或者在思考)错了吗?

1 个答案:

答案 0 :(得分:0)

  

WHERE 1 = 1 AND&#39; num_installazioni&#39; &LT; 5

在此处使用别名 - 您正在检查文字文字 num_installazioni是否“小于”。

https://dev.mysql.com/doc/refman/5.7/en/identifiers.html

它“工作”,因为它不会抛出错误,因为你在WHERE子句中使用了别名(你不能。)如果你认为这给你一个然而,结果是有道理的,你在这里完全是错的。