dev@testdb>select goods_id, goods_name from tb13 group by goods_name; ERROR 1055 (42000): Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testdb.tb13.goods_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
解决方法
把group by字段group_id设成primary key 或者 unique NOT NULL。这个方法在实际操作中没什么意义。
使用函数any_value把报错的字段goods_id包含起来。如, select any_value(goods_id), goods_name from tb13 group by goods_name。
dev@testdb>select * from tb16; +----+----------+--------+-------+ | id | group_id | name | score | +----+----------+--------+-------+ | 1 | A | 小刚 | 20 | | 2 | B | 小明 | 19 | | 3 | B | 小花 | 17 | | 4 | C | 小红 | 18 | +----+----------+--------+-------+ 4 rows in set (0.00 sec) dev@testdb>select any_value(name) as name, group_id, min(score) as score from tb16 group by group_id order by min(score); +--------+----------+-------+ | name | group_id | score | +--------+----------+-------+ | 小明 | B | 17 | | 小红 | C | 18 | | 小刚 | A | 20 | +--------+----------+-------+ 3 rows in set (0.00 sec)
B组的name是小明(因为小明的id更小),而期望结果应该是小花。
所以单纯使用group by无法实现这样的需求。可以使用临时表的方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
dev@testdb>select id, name, t.group_id, t.score from -> (select group_id, min(score) as score from tb16 group by group_id order by min(score)) as t -> inner join tb16 -> on -> t.group_id = tb16.group_id and t.score= tb16.score; +----+--------+----------+-------+ | id | name | group_id | score | +----+--------+----------+-------+ | 1 | 小刚 | A | 20 | | 3 | 小花 | B | 17 | | 4 | 小红 | C | 18 | +----+--------+----------+-------+ 3 rows in set (0.00 sec)