How do I skip one row in an SQL query? - php

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

Related

Get last record id from set of records in mysql query without fetching all records

I have a query that fetches a set of records as shown:
select id
from wallactions
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY)
order by id desc LIMIT $priorRecordsCnt
The LIMIT variable $priorRecordsCnt changes often and can grow very large. It's necessary because i need to know the last id in that set of records based on the $priorRecordsCnt count value.
The problem is, I need to only access the last id in this set, as shown:
$last=array_values(array_slice($result,-1))[0]['id'];
I feel like this is pretty expensive to just get the id of the last record in the set.
Is there a way to optimize this query so it uses the count variable $priorRecordsCnt but i don't need to fetch all the records just to obtain the last value?
The limit clause takes two arguments - an optional offset and the row count. Instead of using $priorRecordsCnt as the record count, you should use it as the offset, and limit the record count to 1:
select id
from wallactions
where status=1 and created > DATE_ADD(NOW(),INTERVAL -1 DAY)
order by id desc LIMIT $priorRecordsCnt, 1
-- Here ---------------------------------^

MySQL - Fetching more records when ordered by integer

So, I'm writing an application to fetch records from the database, and my client has asked if I could sort the data by area. I've got the following query:
SELECT
*
FROM
customers
WHERE
account_type != 'x'
AND
account_type != 'tor'
ORDER BY
area ASC,
id ASC
LIMIT 30
The query returns 30 rows worth of data, all with an area value of 1.
I've got an AJAX query set up to fetch another 30 rows, however as I am ordering the data by area, I am unable to just fit a simple range string to my query as shown in the example below:
...
AND
id > 30
...
How would I write a query that would collect the next 30 records from the database?
Also, there is a record with an area value of 0. This is not shown as the first record in the list. Why is this? And how can I fix this?
Thanks
First, combine the where conditions into a single not in:
SELECT c.*
FROM customers c
WHERE account_type NOT IN ('x', 'tor')
ORDER BY area ASC, id ASC
LIMIT 30;
Then, for the next set, use:
SELECT . . .
OFFSET 30
LIMIT 30
This assumes that id is unique in the table. That is important, because that makes the sort stable.
Have a look at the the SELECT query documentation:
https://dev.mysql.com/doc/refman/5.7/en/select.html
[LIMIT {[offset,] row_count | row_count OFFSET offset}]
In summary, just limit returns you x records. With the offset you can set a starting position, basically allows you for paging.
MySQL LIMIT take an optional parameter offset, so you could send in a parameter telling where to start when picking the 30 results you want
SELECT
*
FROM
customers
WHERE
account_type != 'x'
AND
account_type != 'tor'
ORDER BY
area ASC,
id ASC
LIMIT 30, 30
Should give you the next 30 rows starting from row 30

Select count giving zero rows

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"**;

Counting all rows with a limit

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.

Select latest 10 rows except the first

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!

Categories