I have been working on try to create php web-based paging for our tables
which have over a million rows.
Based on what I have read, I have 3 options
retrieve all rows in resultset - not possiblefor me coz of the size
retrieve 1000 rows, store in temp table and create an iterator for
it and page through it - too many queries - too many inserts!!
run a query each time if someone opts page forward or backwards
Right now I am trying to get option 3 working.
I have the first page showing up as
"select * from accout order by acct fetch first 10 rows only"
Page next
"select * from account where acct>(last record) order by acct fetch
first 10 only"
page last record
"select * from account where acct=(select max(acct) from account)"
The problem is showing the previous page and i really would appreciate
help in this.
SELECT *
FROM (
SELECT
*,
ROW_NUMBER() OVER (ORDER BY acct) AS RowNum
FROM
account
) AS Data
WHERE
RowNum BETWEEN 100 AND 110;
First, you should get rid of the SELECT *. Select only the fields you need.
Place an index on acct, this will help the ROW_NUMBER() OVER (ORDER BY acct) construct.
Use a SELECT COUNT(*) FROM account to determine how many pages you will have.
Also read Fastest most/efficient way to do pagination with SQL searching DB2
The LIMIT..OFFSET solution is supported in DB2 10+.. For older versions, you have to enable the MySQL compatibility with:
$ db2set DB2_COMPATIBILITY_VECTOR=MYS
$ db2stop
$ db2start
in db2cmd in order to use that syntax.
SELECT * FROM foo LIMIT 10, 1;
try the limit and offset in mysql..
this mostly use in creating pagination
Related
I am trying to paginate the records fetched into pages of 10 (using PHP AJAX on MSSQL Server 2005). (I am passing SQL as PHP strings to MSSQL server)
I wish to display button for each page (for example if there are 45 records then I wish to display 5 buttons with each button fetching 10 records).
I have came across this code-
SELECT *
FROM ( SELECT ROW_NUMBER() OVER ( ORDER BY OrderDate ) AS RowNum, *
FROM Orders
WHERE OrderDate >= '1980-01-01'
) AS RowConstrainedResult
WHERE RowNum >= 1
AND RowNum <= 10
ORDER BY RowNum
But this is highly ineffective because firstly whole database is fetched then from it 10 rows is fetched every time.
Could anyone suggest some technique (that works with MSSQL server 2005) wihich fetches only 10 rows at a time and not the whole 100 records at a time.
The above method also includes an extra column (it requires a primary key). I wish to get rid of that column too!
Also, since I have to display the page numbers (pagination tabs), I wish to have a count of total number of records beforehand.
Thanks!
Learn to use LINQ. Very efficient.
Edit
Well then.
SELECT *
FROM etc
WHERE Row_Number() BETWEEN '".$startLimit."' AND '".$endLimit."'
Might work for you. Remember to escape the variables so no dangerous code can bass by.
I'm new to Stackoverflow, and I'm pretty new to MSSQL too (I've been using MYSQL for a couple of years now), and I was wondering if anyone could please help me with a query I'm having trouble with?
I've made a story archive page for a site that I'm putting together, and it's working fine, but the only problem is that I want to archive everything except for the top 6 stories in my table.
I came across a piece of code which will ignore the top few results (6 in my case), but I'm a little bit stumped as to how to incorporate it into my query.
I've tried a few things but I keep getting error messages - I think I'm way off track.
Any help that anyone can give me would be hugely appreciated!
Thank you very much in advance:)
This is the query I found:
SELECT *
FROM PageContent
WHERE id NOT IN (
SELECT TOP 6 id
FROM PageContent
ORDER BY date)
This is my query:
SELECT *
FROM (
SELECT *, ROW_NUMBER() OVER (ORDER by PageId desc) AS RowNum
FROM PageContent WHERE pagestory_type = 'latest_news'
) AS MyDerivedTable
WHERE MyDerivedTable.RowNum BETWEEN $qpage_srt and $qpage_fin ORDER by date desc";
If you have SQL Server 2012 you can try:
SELECT *
FROM PageContent
ORDER BY [date]
OFFSET 6 ROWS
Why can't you just use the TOP clause with a select from the table ordered by the column you need? Similar to the sample you found.
SELECT TOP X * -- add fields as needed
FROM PageContent
WHERE pagestory_type = 'latest_news'
ORDER BY PageId DESC
i dont find any difference in your query except the parameter variables
$qpage_srt and $qpage_fin
it should be #qpage_srt and #qpage_fin in Ms sql...
I'm new to this, sorry if the title is confusing. I am building a simple php/mysql gallery of sorts. It will show the newest 25 entries when a user first goes to it, and also allows off-site linking to individual items in the list. If the URL contains an ID, javascript will scroll to it. But if there are 25+ entries, it's possible that my query will fetch the newest results, but omit an older entry that happens to be in the URL as an ID.
That means I need to do something like this...
SELECT * FROM `submissions` WHERE uid='$sid'
But after that has successfully found the submission with the special ID, also do
SELECT * FROM `submissions` ORDER BY `id` DESC LIMIT 0, 25`
So that I can populate the rest of the gallery.
I could query that database twice, but I am assuming there's some nifty way to avoid that. MySQL is also ordering everything (based on newest, views, and other vars) and using two queries would break that.
You could limit across a UNION like this:
(SELECT * FROM submissions WHERE uid = '$uid')
UNION
(SELECT * FROM submissions WHERE uid <> '$uid' ORDER BY `id` LIMIT 25)
LIMIT 25
Note LIMIT is listed twice as in the case that the first query returns a result, we would have 26 results in the union set. This will also place the "searched for" item first in the returned sort result set (with the other 24 results displayed in sort order). If this is not desirable, you could place an ORDER BY across the union, but your searched for result would be truncated if it happened to be the 26th record.
If you need 25 rows with all of them being sorted, my guess is that you would need to do the two query approach (limiting second query to either 24 or 25 records depending on whether the first query matched), and then simply insert the uid-matched result into the sorted records in the appropriate place before display.
I think the better solution is:
SELECT *
FROM `submissions`
order by (case when usid = $sid then 0 else 1 end),
id desc
limit 25
I don't think the union is guaranteed to return results in the order of the union (there is no guarantee in the standard or in other databases).
I'm trying to get 4 random results from a table that holds approx 7 million records. Additionally, I also want to get 4 random records from the same table that are filtered by category.
Now, as you would imagine doing random sorting on a table this large causes the queries to take a few seconds, which is not ideal.
One other method I thought of for the non-filtered result set would be to just get PHP to select some random numbers between 1 - 7,000,000 or so and then do an IN(...) with the query to only grab those rows - and yes, I know that this method has a caveat in that you may get less than 4 if a record with that id no longer exists.
However, the above method obviously will not work with the category filtering as PHP doesn't know which record numbers belong to which category and hence cannot select the record numbers to select from.
Are there any better ways I can do this? Only way I can think of would be to store the record id's for each category in another table and then select random results from that and then select only those record ID's from the main table in a secondary query; but I'm sure there is a better way!?
You could of course use the RAND() function on a query using a LIMIT and WHERE (for the category). That however as you pointed out, entails a scan of the database which takes time, especially in your case due to the volume of data.
Your other alternative, again as you pointed out, to store id/category_id in another table might prove a bit faster but again there has to be a LIMIT and WHERE on that table which will also contain the same amount of records as the master table.
A different approach (if applicable) would be to have a table per category and store in that the IDs. If your categories are fixed or do not change that often, then you should be able to use that approach. In that case you will effectively remove the WHERE from the clause and getting a RAND() with a LIMIT on each category table would be faster since each category table will contain a subset of records from your main table.
Some other alternatives would be to use a key/value pair database just for that operation. MongoDb or Google AppEngine can help with that and are really fast.
You could also go towards the approach of a Master/Slave in your MySQL. The slave replicates content in real time but when you need to perform the expensive query you query the slave instead of the master, thus passing the load to a different machine.
Finally you could go with Sphinx which is a lot easier to install and maintain. You can then treat each of those category queries as a document search and let Sphinx randomize the results. This way you offset this expensive operation to a different layer and let MySQL continue with other operations.
Just some issues to consider.
Working off your random number approach
Get the max id in the database.
Create a temp table to store your matches.
Loop n times doing the following
Generate a random number between 1 and maxId
Get the first record with a record Id greater than the random number and insert it into your temp table
Your temp table now contains your random results.
Or you could dynamically generate sql with a union to do the query in one step.
SELECT * FROM myTable WHERE ID > RAND() AND Category = zzz LIMIT 1
UNION
SELECT * FROM myTable WHERE ID > RAND() AND Category = zzz LIMIT 1
UNION
SELECT * FROM myTable WHERE ID > RAND() AND Category = zzz LIMIT 1
UNION
SELECT * FROM myTable WHERE ID > RAND() AND Category = zzz LIMIT 1
Note: my sql may not be valid, as I'm not a mySql guy, but the theory should be sound
First you need to get number of rows ... something like this
select count(1) from tbl where category = ?
then select a random number
$offset = rand(1,$rowsNum);
and select a row with offset
select * FROM tbl LIMIT $offset, 1
in this way you avoid missing ids. The only problem is you need to run second query several times. Union may help in this case.
For MySQl you can use
RAND()
SELECT column FROM table
ORDER BY RAND()
LIMIT 4
I'm letting the user page through lists of data. I implemented it with 2 sql statements one to get the count and one to let them get the next section. I get the count to show the number of pages and let the user click on any page, such as:
<< < 1 2 3 4 5 > >> 245 Items
SELECT count(*) FROM list;
SELECT * FROM list limit "$start $rows";
I was just wondering if there was a better way. It looks inefficient, particularly since my SQL is complicated with lots of joins and conditions that I have to execute twice.
Thanks
SELECT SQL_CALC_FOUND_ROWS name, email FROM users WHERE name LIKE 'a%' LIMIT 10;
SELECT FOUND_ROWS();
Source: http://www.arraystudio.com/as-workshop/mysql-get-total-number-of-rows-when-using-limit.html