What I need to do is (using PHP) select the latest 10 rows from a table except the first (which has the highest ID). How is this done?
Try something like this:
SELECT * FROM `table`
ORDER BY `id` DESC
LIMIT 1,10
http://dev.mysql.com/doc/refman/5.0/en/select.html
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 (except when using
prepared statements).
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 `table` ORDER BY id DESC LIMIT 1, 10
1 is the offset and 10 is the limit of records it's going to return!
Related
I'm listing products from my database where I select the latest product as a big feature. The rest are sorted by latest product.
So I have two querys which looks like this.
SELECT * FROM products ORDER BY product_id DESC LIMIT 1
and
SELECT * FROM products ORDER BY product_id DESC LIMIT 4
However... This makes the latest product appear twice in my current layout. (The feature).
How do I tell the second query to skip the latest entry?
We can specify the LIMIT clause to start at second row instead, and then fetch next 4 rows.
SELECT * FROM products ORDER BY product_id DESC LIMIT 1,4
Syntax is:
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
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 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):
The table have 11 rows
Query
SELECT COUNT(*) FROM `zars_all` ORDER BY id DESC LIMIT 9,9
Result
Zero Rows, even there are two rows having id 10 and 11
Query
SELECT * FROM `zars_all` ORDER BY id DESC LIMIT 9,9
Result
Two Rows having id 10 and 11
I have tried using column names as value in Count but it does't help. Any help is appreciated and please tell me if I am doing anything wrong here.
Your first sentence SELECT COUNT(*) returns an integer.
That means that the trailing LIMIT 9,9 is setting a minimum of 9 elements and a maximum of 9 elements.
Let’s examine the LIMIT offset, count clause parameters:
The offset specifies the offset of the first row to return.
The count specifies the maximum number of rows to return.
Your offset is out of bounds, that is why you get no rows.
Please remove that and leave it like:
SELECT COUNT(*) FROM `zars_all` ORDER BY id DESC
Waqas,
LIMIT cannot be applied directly along with COUNT instead change your query like
SELECT count(*) FROM (select * from zars_all limit 9,9) as a"**;
I need to filter (using where clauses) the rows in my table, count the total number of rows from this filter and then limit number of rows for pagination.
What is quickest/more efficient?
Count the rows with sql query. Select the rows with a limit with sql query.
Select all rows with sql query. Count the array with PHP. Split the array with PHP.
Or is there another way to count all rows and get a limited set of the results out?
You should use SQL_CALC_FOUND_ROWS and the FOUND_ROWS() function to return the total number of rows even when a LIMIT is applied to the returned results. After you run your query the results will be returned, and then you can run SELECT FOUND_ROWS() to return the total number of rows without having to run the query again.
SELECT SQL_CALC_FOUND_ROWS * FROM my_table WHERE column = 'something' LIMIT 10;
SELECT FOUND_ROWS() AS total_results;
Use two queries, one to retrieve total number of rows, another to get the rows. The first argument in LIMIT clause specifies the offset of the first row ( current_page * post_per_page ), and the second specifies the maximum number of rows to return ( post_per_page ).
SELECT COUNT(*) AS num_rows FROM table;
SELECT * FROM table LIMIT start, length;
The MySQL LIMIT should do the trick for you. This is a more efficient approach, as it helps in fetching only the relevant records to be displayed and nothing else.
Note that the startingIndex, numberOfRecordsPerPage variables should be set before executing the query.
SELECT * FROM MY_TABLE where
(...) //ALL CONDITIONS go here
LIMIT startingIndex, numberOfRecordsPerPage;
From the MySQL Reference
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
In order to identify whether or not to expect any records in return, one must first run the query (with COUNT and without any LIMIT condition):
`SELECT COUNT(*) FROM MY_TABLE where (...) //ALL CONDITIONS go here`
and store it separately. This shall be the total records applicable to the WHERE clauses given.
If the sum startingIndex+numberOfRecordsPerPage is >= TOTAL_COUNT then that paginated set shall be the last of the whole list and the user should not be allowed to click the NEXT button.
PS: Also, as pointed out in the comments, you might want to look at a framework alternative, like Criteria API for Java, to the heavy weightlifting, particularly if your WHERE conditions are also generated dynamically.
I've been searching all over Google and cant seem to come up with the right answer yet ( I'm just probably not searching the correct terms ), I'm trying to get 25 results returned from a database each time but for example what I want to do is:
query 1 should return results 1 - 24
query 2 should return results 25 - 49
and so on.
What would be the best way to do this?
Thanks
They are separate queries althought they return the exact same fields from the exact same tables under the exact same conditions. The difference between them is the LIMIT chunk:
LIMIT startRow, rowsCount
--the first row is the 0th, not 1st.
If your query is like:
select * from mytable where field1 = "value1"
you must execute two separate queries (or as much queries as you want):
select * from mytable where field1 = "value1" LIMIT 0, 25
-- will return the first 25 rows
select * from mytable where field1 = "value1" LIMIT 25, 25
-- will return 25 rows starting from the row 25
general formula: If you want to fetch a specific page N (starting from 1), where each page has M elements, you must append to your query:
$yourquery = "select * from mytable where myfield = 'myvalue'";
$yourquery .= sprintf(" LIMIT %d, %d", ($page-1)*$itemsPerPage, $itemsPerPage);
$result = mysql_query($yourquery, $yourconnection);
Disclaimers:
mysql_ is deprecated. use mysqli_ instead.
never use, in real production code, sprintf for your parameters unless you know what are you doing, since you could expose a SQL Injection hole.
Edit You can use ANY elements you want to do LIMIT. Usually, pages have constant size, but since you want irregular sizes (page 1 24 elements, page 2 25 elements, you should) use the following LIMITs:
LIMIT 0, 24
--gets the first 24 (say 1st to 24th) elements
LIMIT 24, 25
--gets the following 25 items (say 25th to 49th)
From the manual:
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 (except when using
prepared statements).
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
So in your case:
SELECT * FROM `table_name` LIMIT 0,25
SELECT * FROM `table_name` LIMIT 25,25
(SELECT *
FROM mytable
LIMIT 0,24)
UNION
(SELECT *
FROM
mytable
LIMIT 24,25)
ORDER BY someSortOfId;
Note that there should be at least one column with unique values (such as an ID), or the result sets will overlap.
SELECT * FROM `table_name` LIMIT 0,25 // This will give you 1-24 records
SELECT * FROM `table_name` LIMIT 25,25 // This will give you 25-49 records
I have a SQL query which loads the first 20 picture results from a database, I would like to give users the option to view more than 20 if they want to, or even create a tab to see the next 20 pictures, I'm stumped on how to input this code I'm sure its straight forward but I'm in a brain fart mode and really need to get over this hurdle.
Look into LImit and offset features in MYSQL
https://dev.mysql.com/doc/refman/5.0/en/select.html
Excerpt from above link:
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 (except when using prepared statements).
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