我有一张桌子
+------+-----+-------+
| name | age | class |
+------+-----+-------+
| Ben | 4 | B |
| Alex | 7 | A |
| Jim | 3 | B |
| Ben | 5 | C |
| Ben | 2 | C |
| Alex | 9 | A |
+------+-----+-------+
我需要一个查询,以便我可以选择年龄最小的人:
+------+-----+-------+
| name | age | class |
+------+-----+-------+
| Ben | 2 | C |
| Jim | 3 | B |
| Alex | 7 | A |
+------+-----+-------+
我一直在搞乱各种组合或GROUP BY和ORDER BY,似乎无法做到正确。
此外,该表包含大约800万条记录,因此性能非常重要。
答案 0 :(得分:3)
首先,您必须选择每个班级的最低年龄:
select min(age) as age, class as class from t group by class
(注意:我假设你想要每个班级的最低年龄。我想要每个名字的最小年龄,然后在查询中用class
替换name
...)
然后,您必须将结果与表连接以获取相应的行。 完整的SQL将是
select t.* from t
inner join
(
select min(age) as age, class as class from t group by class
) min_ages on t.age = min_ages.age and t.class = min_ages.class;
为获得最佳效果,请确保age
已编入索引以及class
(或name
,无论您想要group by
表达式中的哪一个。)
答案 1 :(得分:0)
SELECT name,age,class FROM table t1
JOIN
(SELECT name,MIN(age)as minage FROM table GROUP BY name)t2
ON t1.name=t2.name AND t1.age=t2.minage