学习成长

提供在线文档,方便大家学习


where与having区别

<pre><code>CREATE TABLE `students` ( `stu_no` int(11) NOT NULL, `grade` int(11) NOT NULL, `from_date` date NOT NULL, `to_date` date NOT NULL, PRIMARY KEY (`stu_no`,`from_date`));</code></pre> <p>分析下面两句SQL:</p> <pre><code>select stu_no,count(stu_no) as t from students group by stu_no HAVING t &gt; 15; select stu_no,count(stu_no) as t from students where count(stu_no) &gt; 15 group by stu_no;</code></pre> <p>1.WHERE语句在GROUP BY语句之前;SQL会在分组之前计算WHERE语句 2.HAVING语句在GROUP BY语句之后;SQL会在分组之后计算HAVING语句。所以第二种方法是错误的. 3.sql语句的执行过程是:from--&gt;where--&gt;group by --&gt;having --- &gt;order by --&gt; select; 4.聚合函数是针对结果集进行的,where之后并不是结果集,所以主函数放在where语句中,会出现错误, 5.而having是针对结果集做筛选,用having来代替where,having一般跟在group by后</p>

页面列表

ITEM_HTML