且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MySQL:选择N行,但在一列中仅包含唯一值

更新时间:2022-12-09 19:35:56

可能不是最优雅的解决方案,并且IN的性能可能在较大的表上受到影响.

Probably not the most elegant of solutions, and the performance of IN may suffer on larger tables.

嵌套查询获取每个城市的最小Birthyear.只有具有此Birthyear的记录才在外部查询中匹配.按年龄排序,然后限制为3个结果,则可以使您成为所在城市中年龄最大的3个最老的人(Egon Spengler退学..)

The nested query gets the minimum Birthyear for each city. Only records who have this Birthyear are matched in the outer query. Ordering by age then limiting to 3 results gets you the 3 oldest people who are also the oldest in their city (Egon Spengler drops out..)

SELECT Name, City, Birthyear, COUNT(*) AS ct
FROM table
WHERE Birthyear IN (SELECT MIN(Birthyear)
               FROM table
               GROUP by City)
GROUP BY City
ORDER BY Birthyear DESC LIMIT 3;

+-----------------+-------------+------+----+
| name            | city        | year | ct |
+-----------------+-------------+------+----+
| Henry Jones     | Chicago     | 1899 | 1  |
| Mac Taylor      | New York    | 1955 | 1  |
| Sarah Connor    | Los Angeles | 1959 | 1  |
+-----------------+-------------+------+----+

编辑-在外部查询中添加了GROUP BY City,因为出生年限相同的人将返回多个值.对外部查询进行分组可确保每个城市仅返回一个结果,如果超过一个人的最小值为Birthyear. ct列将显示该城市中是否有不止一个人与那个Birthyear

Edit - added GROUP BY City to outer query, as people with same birth years would return multiple values. Grouping on the outer query ensures that only one result will be returned per city, if more than one person has that minimum Birthyear. The ct column will show if more than one person exists in the city with that Birthyear