#通过列名分组 dev@testdb>SELECT sex FROM tb8 GROUP BY sex; +------+ | sex | +------+ | 0 | | 1 | +------+ 2 rows in set (0.00 sec) # 通过列的位置进行分组, 这个列的位置指的是select_expr中列的位置,如sex 在select_expr的第一位; #列位置分组一般不建议; dev@testdb>SELECT sex FROM tb8 GROUP BY 1; +------+ | sex | +------+ | 0 | | 1 | +------+ 2 rows in set (0.00 sec) # 按照多个关键字进行分组; dev@testdb>select * from tb8 group by id, age, password asc; +----+----------+----------+-----+------+ | id | username | password | age | sex | +----+----------+----------+-----+------+ | 1 | Tom | 123 | 30 | 0 | | 2 | Jack | 123 | 23 | 0 | | 4 | Mike | 111 | 20 | 1 | +----+----------+----------+-----+------+ 3 rows in set, 1 warning (0.00 sec) # select_expr为*时, group by 中应包括primary key id; dev@testdb>select * from tb8 group by age; ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testdb.tb8.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by # 当select expr 为指定字段时, 可以对其进行多关键字分组和排序; dev@testdb>select password from tb8 group by password, username desc; +----------+ | password | +----------+ | 111 | | 123 | | 123 | +----------+ 3 rows in set, 1 warning (0.00 sec) dev@testdb>
显然通过分组可以去重;
可以对分组进行排序;
当select_expr是(*)时,group by 子句中应有primary key 在内进行分组, 否则会出错;
dev@testdb>select sex, age from tb8 group by sex having age > 22; ERROR 1055 (42000): Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testdb.tb8.age' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
dev@testdb>select sex, age from tb8 group by sex, age having age > 22; +------+-----+ | sex | age | +------+-----+ | 0 | 30 | | 0 | 23 | +------+-----+ 2 rows in set (0.00 sec) dev@testdb>select sex, max(age) from tb8 group by sex; +------+----------+ | sex | max(age) | +------+----------+ | 0 | 30 | | 1 | 20 | +------+----------+ 2 rows in set (0.00 sec) dev@testdb>select sex, max(age) as age from tb8 group by sex having age > 22; +------+------+ | sex | age | +------+------+ | 0 | 30 | +------+------+ 1 row in set (0.00 sec) dev@testdb>select sex, age from tb8 group by sex, age having age > 22; +------+-----+ | sex | age | +------+-----+ | 0 | 30 | | 0 | 23 | +------+-----+ 2 rows in set (0.00 sec)