例如,我想知道谁是某些人群中最高的人。我用
SELECT name, height
FROM people
WHERE height = (SELECT MAX(height) FROM people)
但它看起来不太好。最好的方法是什么?
答案 0 :(得分:6)
您可以使用LIMIT
(MySQL)或top
(MsSQL):
SELECT name, height FROM people ORDER BY height DESC LIMIT 1;
SELECT TOP 1 name, height FROM people ORDER BY height DESC;
这将获得1条记录。
要获得更多记录,您的子查询可以正常工作。如果您不喜欢子查询,可以使用这些查询(MySQL):
SELECT MAX(height) INTO @maxHeight FROM person ORDER BY height DESC LIMIT 1;
SELECT * FROM person WHERE height = @maxHeight;
这样您就可以在其他查询中重复使用@maxHeight
(对于当前连接)。
答案 1 :(得分:1)
如果您使用SQL Server,那么
SELECT TOP 1 name, height
FROM people
ORDER BY height DESC
SQL Server不支持LIMIT
方法,因此您需要使用TOP
所以如果你使用MySQL:
SELECT name, height
FROM people
ORDER BY height DESC LIMIT 1
OR
如果您担心超过1人的身高最高,可以使用子查询:
SELECT name, height
FROM people
WHERE height = (SELECT TOP 1 height FROM people ORDER BY height DESC)
ORDER BY name
当然与MySQL相同的例子:
SELECT name, height
FROM people
WHERE height = (SELECT height FROM people ORDER BY height DESC LIMIT 1)
ORDER BY name
答案 2 :(得分:0)
假设你正在使用MySQL:
SELECT name, height
FROM people
ORDER BY ABS(height) DESC LIMIT 1