0
点赞
收藏
分享

微信扫一扫

WHERE, HAVING, GROUP BY in SQL

他说Python 2022-02-18 阅读 68

Some notes:

1. The aggregated functions cannot be present in WHERE clause.

Below is incorrect:

Error Code: 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 '(salary) > 10000 LIMIT 0, 1000' at line 3

2. The aggragated functions can be used in HAVING clause for filtering.

Below is incorrect, because we need to note 3.

3. HAVING must be used along with GROUP BY

Below is correct.

4. HAVING must be used after GROUP BY.

5. When using GROUP BY, the fields(except aggregated functions) in SELECT must be present in GROUP BY. The fields present in GROUP BY is not necessary in SELECT.

Error Code: 1055
Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'atguigudb.employees.job_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

5. Conclusion

- WHERE: filtering firstly, then connecting tables. More efficient. Incompatible with aggregated functions.

- HAVING: connecting tables firstly, then filtering. Usually with aggregated functions, and must follow GROUP BY.

举报

相关推荐

0 条评论