MySQL 中是否有 TOP 的替代方案?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2249905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:16:41  来源:igfitidea点击:

Is there an alternative to TOP in MySQL?

sqlmysql

提问by Avinash

I want to know the alternative of the TOP keyword as in MySQL. I have read about TOPin SQL Server.

我想知道 MySQL 中 TOP 关键字的替代方法。我已经阅读了SQL Server 中的TOP

Is there any alternative to this in MySQL, or any other method in MySQL from which we can get same functionality?

在 MySQL 中是否有任何替代方法,或者在 MySQL 中我们可以获得相同功能的任何其他方法?

回答by Sampson

Ordering and limiting the results:

排序和限制结果:

SELECT field1, field2
FROM myTable
ORDER BY field1 ASC
LIMIT 10

回答by Pascal MARTIN

You can use the LIMITkeyword (See the documentation of the SELECTinstruction)-- it goes at the end of the query :

您可以使用LIMIT关键字(见的的文件SELECT指令-它会在查询的结尾:

select *
from your_table
where ...
limit 10

to get the top 10 lines

获得前 10 行


Or even :


甚至 :

select *
from your_table
where ...
limit 5, 10

To get 10 lines, startig from the 6th (i.e. getting lines 6 to 15).

要获得 10 行,请从第 6 行开始(即获得第 6 行到第 15 行)

回答by nuvio

I know this question has been answered by I'd like to add some Performance consideration. The TOP operator in MySQL is not translated with LIMIT.

我知道这个问题已经回答了我想添加一些性能方面的考虑。MySQL 中的 TOP 运算符不使用 LIMIT 进行转换。

Suppose you want to get the last 10 persons inserted in the db:

假设您想在数据库中插入最后 10 个人:

SELECT name, id
FROM persons
ORDER BY id DESC
LIMIT 10

However this could became extremely slow when using thousands of rows.

然而,当使用数千行时,这可能会变得非常慢。

A much faster solution would be retrieve the current number X of rows:

一个更快的解决方案是检索当前行数 X:

SELECT COUNT(*) FROM persons

and use that number to query for the last 10:

并使用该数字查询最后 10 个:

SELECT name, id
    FROM persons
    LIMIT x-10,10

So limit will skip the first X-10 rows and return the next 10. This was 100 times faster for me than sorting the column, but this is just my experience.

所以 limit 将跳过前 X-10 行并返回接下来的 10 行。这对我来说比对列进行排序快 100 倍,但这只是我的经验。

回答by Gopi

mysql equivalent of topand you can find further more about LIMITin MySql Doc

mysql 相当于 top,您可以在MySql Doc 中找到有关LIMIT 的更多信息

回答by Sarfraz

yes, there is the limitclause.

是的,有限制条款。

Example:

例子:

    SELECT * FROM `your_table` LIMIT 0, 10 

This will display the first 10 results from the database.

这将显示数据库中的前 10 个结果。