mysql>select name,age fromusergroupby age; ERROR 1055 (42000): Expression #1ofSELECT list isnotinGROUPBY clause andcontains nonaggregated column'school.user.name' which isnot functionally dependent on columns inGROUPBY clause; this is incompatible with sql_mode=only_full_group_by mysql>
mysql>select*fromuser; +----+----------+-----+-----+ | id | name | age | sex | +----+----------+-----+-----+ |1| zhangsan |16| W | |2| lisi |21| M | |3| laoliu |24| W | |4| jianzhe |16| W | |5| wangwei |21| M | +----+----------+-----+-----+ 5rowsinset (0.00 sec)
mysql>select age fromusergroupby age; +-----+ | age | +-----+ |16| |21| |24| +-----+ 3rowsinset (0.00 sec)
mysql>select age,sum(age) fromusergroupby age having age >20; +-----+----------+ | age |sum(age) | +-----+----------+ |21|42| |24|24| +-----+----------+ 2rowsinset (0.00 sec)
mysql>select age,sum(age) fromuserwhere age >20groupby age;#推荐使用where,age有索引的话where可以使用索引 +-----+----------+ | age |sum(age) | +-----+----------+ |21|42| |24|24| +-----+----------+ 2rowsinset (0.00 sec)
mysql>select age,sex,count(*) fromusergroupby age,sex; +-----+-----+----------+ | age | sex |count(*) | +-----+-----+----------+ |16| W |2| |21| M |2| |24| W |1| +-----+-----+----------+ 3rowsinset (0.00 sec)
mysql>
mysql>select age,sex,count(id) fromusergroupby age,sex orderby age desc; +-----+-----+-----------+ | age | sex |count(id) | +-----+-----+-----------+ |24| W |1| |21| M |2| |16| W |2| +-----+-----+-----------+ 3rowsinset (0.01 sec)
mysql>
其实,从上面可以看出,其实order by内部实际上是进行了排序的,我们使用explain查看
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
mysql> explain select age fromusergroupby age; +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+ | id | select_type |table| partitions | type | possible_keys | key | key_len |ref|rows| filtered | Extra | +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+ |1| SIMPLE |user|NULL|ALL|NULL|NULL|NULL|NULL|5|100.00|Using temporary | +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-----------------+ 1rowinset, 1 warning (0.00 sec)
mysql> explain select name fromusergroupby name; +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-------------+ | id | select_type |table| partitions | type | possible_keys | key | key_len |ref|rows| filtered | Extra | +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-------------+ |1| SIMPLE |user|NULL| index | name | name |202|NULL|5|100.00|Using index | +----+-------------+-------+------------+-------+---------------+------+---------+------+------+----------+-------------+ 1rowinset, 1 warning (0.00 sec)