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

后端 未结 5 796
有刺的猬
有刺的猬 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:17

    If there is a unique key on the table yes...

    Select * From Table O
    Where (Select Count(*) From Table I
           Where [UniqueKeyValue] < O.UniqueKeyValue)  < N
    

    You can substitute your own criteria if you want the "Top" definition to be based on some other logic than on the unique key...

    EDIT: If the "sort" that defines the meaning of "Top" is based on a non-unique column, or set of columns, then you can still use this, but you can't guarantee you will be able to get exactly N records out...

      Select * From Table O
      Where (Select Count(*) From Table I
             Where nonUniqueCol < O.nonUniqueCol) < 10
    

    If records 8, 9, 10, 11, and 12 all have the same value in [nonUniqueCol], then the query will either only generate 7 records, (with '<') ... , or 12 (if you use '<=')

    NOTE: As this involves a correlated sub-query, the performance can be an issue for very large tables...

提交回复
热议问题