table: employee(id,name,depart_id,depart_name,wage)
select depart_name,AVG(wage)
from employee
group by depart_id
order by depart_name
我想问的是,这个查询对吗?就是说select子句中没有出现的depart_id字段能不能出现在group或者order子句中?
多谢了!
brayden这个能执行真的很奇怪。(可能是各数据库有差距。) ORACLE中分组函数,出现在select后的字段要不是group by的字段,要么是分组函数,如楼主的avg函数。但是出现在group by子句中的字段可以不出现在select字句中。
没有问题. select子句中没有出现的字段 可以出现在group字句, 可以出现在order子句中. mysql 5.5马上做个实验:
mysql> create table test2(a int, b int, c int);
Query OK, 0 rows affected (0.22 sec)
mysql> insert into test2 values(1, 1,1), (2,2,2),(3,3,3);
Query OK, 3 rows affected (0.03 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select a from test2 group by b order by c;
+------+
| a |
+------+
| 1 |
| 2 |
| 3 |
+------+
3 rows in set (0.00 sec)
如果我没记错的话,出现在select子句中的字段要么出现在group by子句中,要么出现在聚合函数中(如AVG,SUM,COUNT,MIN,MAX),这是为了分组统计的需要。而出现在group by子句中的字段不一定要出现在select子句中。
问题的逻辑本身就有问题,需要知道的规则是: 使用了group by 之后,select和order子句中出现的字段,必须出现在group by子句中,或者是其他字段的聚合运算(如,min,max,avg等)
至于问题“select子句中没有出现的departid字段能不能出现在group或者order子句中”,如要非要回答的话:
1. order子句可以是表中的任意字段,和select子句没有关系,所以departid是可以出现在order子句中。
2. group子句也能够出现depart_id,因为group子句能出现哪些语句也和select子句有哪些字段没关系,如下面的语句语法上是没有错误的。
select depart_name,AVG(wage)
from employee
group by depart_id, depart_name
order by depart_name
不对 ... SELECT 子句中没有出现的字段 可以 出现在 ORDER 字句中 ...
不可以 出现在 GROUP BY 子句中 ...