📜  SQL 中 Where 和 Have 子句的区别

📅  最后修改于: 2021-09-09 10:17:09             🧑  作者: Mango

1. WHERE 条款:
WHERE 子句用于过滤表中的记录或在连接多个表时使用。只有那些满足 WHERE 子句中指定条件的记录才会被提取。它可以与 SELECT、UPDATE、DELETE 语句一起使用。

让我们考虑下表“学生”

Roll_no       S_Name      Age

1                a             17

2                b             20

3                c             21

4                d             18

5                e             20

6                f             17

7                g             21

8                h             17 

考虑查询:

SELECT S_Name, Age FROM Student 
WHERE Age >=18

上述查询的输出是:

S_Name      Age

b             20             

c             21             

d             18             

e             20             

g             21             

2. 有条款:
HAVING 子句用于根据 HAVING 子句中的给定条件从组中过滤记录。满足给定条件的组将出现在最终结果中。 HAVING 子句只能使用
用 SELECT 语句。

让我们考虑上面提到的 Student 表并在其上应用带有子句:

SELECT Age, COUNT(Roll_No) AS No_of_Students 
FROM Student GROUP BY Age
HAVING COUNT(Roll_No) > 1 

上述查询的输出是:

Age     No_of_Students

17              3

20              2

21              1 

SQL 中 Where 和 Have 子句的区别:

SR.NO. WHERE Clause HAVING Clause
1. WHERE Clause is used to filter the records from the table based on the specified condition. HAVING Clause is used to filter record from the groups based on the specified condition.
2. WHERE Clause can be used without GROUP BY Clause HAVING Clause cannot be used without GROUP BY Clause
3. WHERE Clause implements in row operations HAVING Clause implements in column operation
4. WHERE Clause cannot contain aggregate function HAVING Clause can contain aggregate function
5. WHERE Clause can be used with SELECT, UPDATE, DELETE statement. HAVING Clause can only be used with SELECT statement.
6. WHERE Clause is used before GROUP BY Clause HAVING Clause is used after GROUP BY Clause
7. WHERE Clause is used with single row function like UPPER, LOWER etc. HAVING Clause is used with multiple row function like SUM, COUNT etc.