Is there an alternative to TOP in MySQL?

前端 未结 5 2162
慢半拍i
慢半拍i 2020-11-28 15:19

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

Is there any alternative to this in MySQL, or any other method i

相关标签:
5条回答
  • 2020-11-28 15:29

    You can use the LIMIT keyword (See the documentation of the SELECT instruction) -- it goes at the end of the query :

    select *
    from your_table
    where ...
    limit 10
    

    to get the top 10 lines


    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).

    0 讨论(0)
  • 2020-11-28 15:32

    mysql equivalent of top and you can find further more about LIMIT in MySql Doc

    0 讨论(0)
  • 2020-11-28 15:34

    yes, there is the limit clause.

    Example:

        SELECT * FROM `your_table` LIMIT 0, 10 
    

    This will display the first 10 results from the database.

    0 讨论(0)
  • 2020-11-28 15:43

    Ordering and limiting the results:

    SELECT field1, field2
    FROM myTable
    ORDER BY field1 ASC
    LIMIT 10
    
    0 讨论(0)
  • 2020-11-28 15:47

    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.

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

    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:

    SELECT COUNT(*) FROM persons
    

    and use that number to query for the last 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.

    0 讨论(0)
提交回复
热议问题