在一个包含城市的表格中,我希望获得五个最大的城市并按名称命名:
SELECT * FROM cities ORDER BY population DESC LIMIT 5
这让我成为按人口排序的最大城市,但我希望按名称排列相同的城市。有没有一种简单的方法可以做到这一点(没有转向子查询或事后用PHP对城市进行排序)?
答案 0 :(得分:9)
我认为你想要的是:
( SELECT * FROM cities ORDER BY population DESC LIMIT 5 ) ORDER BY name;
答案 1 :(得分:1)
SELECT * FROM cities ORDER BY population desc, name LIMIT 5
答案 2 :(得分:0)
SELECT * FROM cities ORDER BY population DESC, name LIMIT 5
你尝试过这个吗?我认为这可以工作
答案 3 :(得分:0)
简单地做
SELECT y.*
FROM (SELECT name FROM cities ORDER BY population DESC LIMIT 5) AS x,
cities AS y
WHERE x.name = y.name
ORDER BY y.name
这就是它的全部内容。
干杯。
答案 4 :(得分:0)
您将需要一个子查询:
SELECT a.*
FROM (
SELECT *
FROM cities
ORDER BY population DESC
LIMIT 5
) a
ORDER BY name;
编辑:刚看到你不想要子查询。为什么不?这是一个非常快速返回的有效查询(对于有或没有子查询的人口应该有一个索引)。
答案 5 :(得分:0)
mysql> create temporary table temp ( ID int );
mysql> insert into temp select ID from cities order by population desc limit 5;
mysql> select a.* from cities a,temp b where a.ID=b.ID order by Name;
关闭连接时会删除临时表,也可以手动删除它们。从其他连接中看不到临时表。 通常的方式是(但它尚不支持):
mysql> select * from cities where ID in (select ID from cities order by population desc limit 5) order by Name;
但答案是:
ERROR 1235 (42000): This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'
(试过5.0.5)