sql having 函数 按匿名字段作为条件进行查询

今天写sql 遇到一个问题

  SELECT a.*, count(b.id) AS nums
  FROM a
  LEFT JOIN b ON a.id=b.a_id
  WHERE nums>1

这时候会报错误
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ......
原因: 是因为 nums为匿名字段, 是在sql执行完以后生成的字段. 现在执行where 语句的时候,整个sql 还并未执行完毕,并没有生成nums
解决: 如果想要达到效果,可以试用having 方法 将sql 变成为

  SELECT a.*, count(b.id) AS nums
  FROM a
  LEFT JOIN b ON a.id=b.a_id
  HAVING nums>1

   为什么现在HAVING 能行呢,因为执行顺序中,having是在整个sql执行完之后执行的,对内存有一些消耗

       
原文地址:https://www.cnblogs.com/zhaoyang-1989/p/4566398.html