Can there be a database-agnostic SQL query to fetch top N rows?

后端 未结 5 803
有刺的猬
有刺的猬 2021-01-28 05:33

We want to be able to select top N rows using a SQL Query. The target database could be Oracle or MySQL. Is there an elegant approach to this? (Needless to say, we\'re dealing w

5条回答
  •  再見小時候
    2021-01-28 06:36

    The big problem, after looking this over, is that MySQL isn't ISO SQL:2003 compliant. If it was, you'd have these handy windowing functions:

    SELECT * from
    (   SELECT
        RANK() OVER (ORDER BY ) AS ranking,
        ,
        FROM 
    )
    WHERE ranking <= 
    
    
    

    Alas, MySQL (and others that mimic it's behavior, eg SQLite), do not, hence the whole limiting issue.

    Check out this snippet from Wikipedia (http://en.wikipedia.org/wiki/Window_function_(SQL)#Limiting_result_rows)

    提交回复
    热议问题