select dept_id ,name, count(name) as total from employees group by dept_id having total < ( select count(name) from employees where dept_id=( select dept_id from departments where dept_name='开发部') ); ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'tarena.employees.name' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
时间: 2024-03-14 13:43:23 浏览: 109
学习SQL语句(强大的group by与select from模式)
这个错误是因为在 MySQL 5.7.5 以后的版本中,SQL_MODE 默认设置为 ONLY_FULL_GROUP_BY,表示在 GROUP BY 子句中的列以外的任何列都必须在聚合函数中使用,或者在 GROUP BY 子句中列出。在您的 SQL 语句中,SELECT 子句中的 name 列未在 GROUP BY 子句中列出,也未在聚合函数中使用。
您可以通过以下两种方法解决这个问题:
1. 将 SQL_MODE 设置为兼容的模式(例如,将其设置为 '' 或 'TRADITIONAL'):
```sql
SET sql_mode = '';
SELECT dept_id, name, COUNT(name) AS total
FROM employees
GROUP BY dept_id
HAVING total < (SELECT COUNT(name) FROM employees WHERE dept_id = (SELECT dept_id FROM departments WHERE dept_name = '开发部'));
```
2. 在 SELECT 子句中使用聚合函数:
```sql
SELECT dept_id, MAX(name) AS name, COUNT(name) AS total
FROM employees
GROUP BY dept_id
HAVING total < (SELECT COUNT(name) FROM employees WHERE dept_id = (SELECT dept_id FROM departments WHERE dept_name = '开发部'));
```
这两个查询的结果应该是一样的。
阅读全文