开发者

Grab a certain amount of database entries from a table

Is there a way to grab an exact amount of entries from a database example. For example say you had a table that just had an id and total visits for the columns. Say you wanted to grab exactly 20 entries and sort them by total visits. How would you go about this? I 开发者_StackOverflow中文版know how to sort the whole table, but would like to be able to grab the top twenty total visits and then sort them. Thanks

O and right now I am using sqlite, but I know in the future I will be using mysql also. Thanks


Try with:

SELECT * FROM TableName ORDER BY TotalVisits LIMIT 20


using limit to get the top 20,

and if you want to add another sort, add it after visit column

like :

SELECT * FROM mytable ORDER BY visits DESC 

/*here put another order by field like date */
, date

LIMIT 20


Use ORDER - LIMIT clause

SELECT * FROM table ORDER BY field [ASC|DESC] LIMIT 20 OFFSET [offset value]


You need to use LIMIT, but you will need to put the whole thing in a subquery if you intend to re-sort the top 20 based on separate criteria. So

SELECT * from <table> order by <total visits column> LIMIT 20

will get you the top 20, but then to sort within that result you would do something like

SELECT * from 
  (SELECT * from <table> ORDER BY <total visits column> LIMIT 20) 
  ORDER BY <other criteria>


The LIMIT clause can be used to constrain the number of rows returned by the SELECT statement. LIMIT takes one or two numeric arguments, which must both be nonnegative integer constants, with these exceptions:

With two arguments, the first argument specifies the offset of the first row to return, and the second specifies the maximum number of rows to return. The offset of the initial row is 0 (not 1):

SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

With one argument, the value specifies the number of rows to return from the beginning of the result set:

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows

In other words, LIMIT row_count is equivalent to LIMIT 0, row_count.

All on: http://dev.mysql.com/doc/refman/5.5/en/select.html better explnation for mysql, however sqlite works same way: http://www.sqlite.org/lang_select.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜